<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
  <!-- <link rel="stylesheet/less" href="bootstrap/less/bootstrap.less">
  <script src="bootstrap/less/less-1.3.3.min.js"></script>
  -->
  <link href="bootstrap/bootstrap.css" type="text/css" rel="stylesheet"/>
  <link href="google-code-prettify/prettify.css" type="text/css" rel="stylesheet"/>
  <script type="text/javascript" src="google-code-prettify/prettify.js"></script>
  <link href="css/vertx.css" type="text/css" rel="stylesheet"/>
  <link href="css/sunburst.css" type="text/css" rel="stylesheet"/>
  <title>Vert.x</title>
  <script>
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-30144458-1']);
    _gaq.push(['_trackPageview']);
    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
  </script>
</head>

<body onload="prettyPrint()" class="hp">

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">

      <a class="btn btn-navbar" data-toggle="collapse"
         data-target=".nav-collapse">
        <span class="i-bar"></span>
        <span class="i-bar"></span>
        <span class="i-bar"></span>
      </a>

      <a class="brand" href="/">Vert.x</a>

      <div class="nav-collapse">
        <ul class="nav">
          <li><a href="/">Home</a></li>
          <li><a href="downloads.html">Download</a></li>
          <li><a href="install.html">Install</a></li>
          <li><a href="docs.html">Documentation</a></li>
          <li><a href="examples.html">Examples</a></li>
          <li><a href="community.html">Project Info</a></li>
          <li><a href="https://github.com/vert-x/vert.x">Github</a></li>
          <li><a href="http://modulereg.vertx.io/">Module Registry</a></li>
          <li><a href="http://groups.google.com/group/vertx">Google Group</a></li>
          <li><a href="http://vertxproject.wordpress.com/">Blog</a></li>
        </ul>
      </div>
    </div>
  </div>
</div>

<div class="container">

  <div class="row">
    <div class="span12">
      <div class="well">
        <h1>Java API Manual</h1>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="span12">
      <div class="well">
<div>


<div class="toc">
<ul>
<li><a href="#writing-verticles">Writing Verticles</a><ul>
<li><a href="#asynchronous-start">Asynchronous start</a></li>
<li><a href="#verticle-clean-up">Verticle clean-up</a></li>
<li><a href="#the-container-object">The container object</a></li>
<li><a href="#the-vertx-object">The vertx object</a></li>
<li><a href="#getting-configuration-in-a-verticle">Getting Configuration in a Verticle</a></li>
<li><a href="#logging-from-a-verticle">Logging from a Verticle</a></li>
<li><a href="#accessing-environment-variables-from-a-verticle">Accessing environment variables from a Verticle</a></li>
<li><a href="#causing-the-container-to-exit">Causing the container to exit</a></li>
</ul>
</li>
<li><a href="#deploying-and-undeploying-verticles-programmatically">Deploying and Undeploying Verticles Programmatically</a><ul>
<li><a href="#deploying-a-simple-verticle">Deploying a simple verticle</a></li>
<li><a href="#deploying-worker-verticles">Deploying Worker Verticles</a></li>
<li><a href="#deploying-a-module-programmatically">Deploying a module programmatically</a></li>
<li><a href="#passing-configuration-to-a-verticle-programmatically">Passing configuration to a verticle programmatically</a></li>
<li><a href="#using-a-verticle-to-co-ordinate-loading-of-an-application">Using a Verticle to co-ordinate loading of an application</a></li>
<li><a href="#specifying-number-of-instances">Specifying number of instances</a></li>
<li><a href="#getting-notified-when-deployment-is-complete">Getting Notified when Deployment is complete</a></li>
<li><a href="#undeploying-a-verticle-or-module">Undeploying a Verticle or Module</a></li>
</ul>
</li>
<li><a href="#scaling-your-application">Scaling your application</a></li>
<li><a href="#the-event-bus">The Event Bus</a><ul>
<li><a href="#the-theory">The Theory</a><ul>
<li><a href="#addressing">Addressing</a></li>
<li><a href="#handlers">Handlers</a></li>
<li><a href="#publish-subscribe-messaging">Publish / subscribe messaging</a></li>
<li><a href="#point-to-point-and-request-response-messaging">Point to point and Request-Response messaging</a></li>
<li><a href="#transient">Transient</a></li>
<li><a href="#types-of-messages">Types of messages</a></li>
</ul>
</li>
<li><a href="#event-bus-api">Event Bus API</a><ul>
<li><a href="#registering-and-unregistering-handlers">Registering and Unregistering Handlers</a></li>
<li><a href="#publishing-messages">Publishing messages</a></li>
<li><a href="#sending-messages">Sending messages</a></li>
<li><a href="#replying-to-messages">Replying to messages</a><ul>
<li><a href="#specifying-timeouts-for-replies">Specifying timeouts for replies</a></li>
<li><a href="#getting-notified-of-reply-failures">Getting notified of reply failures</a></li>
</ul>
</li>
<li><a href="#message-types">Message types</a></li>
</ul>
</li>
<li><a href="#distributed-event-bus">Distributed event bus</a></li>
</ul>
</li>
<li><a href="#shared-data">Shared Data</a><ul>
<li><a href="#shared-maps">Shared Maps</a></li>
<li><a href="#shared-sets">Shared Sets</a></li>
</ul>
</li>
<li><a href="#buffers">Buffers</a><ul>
<li><a href="#creating-buffers">Creating Buffers</a></li>
<li><a href="#writing-to-a-buffer">Writing to a Buffer</a><ul>
<li><a href="#appending-to-a-buffer">Appending to a Buffer</a></li>
<li><a href="#random-access-buffer-writes">Random access buffer writes</a></li>
</ul>
</li>
<li><a href="#reading-from-a-buffer">Reading from a Buffer</a></li>
<li><a href="#other-buffer-methods">Other buffer methods:</a></li>
</ul>
</li>
<li><a href="#json">JSON</a></li>
<li><a href="#delayed-and-periodic-tasks">Delayed and Periodic Tasks</a><ul>
<li><a href="#one-shot-timers">One-shot Timers</a></li>
<li><a href="#periodic-timers">Periodic Timers</a></li>
<li><a href="#cancelling-timers">Cancelling timers</a></li>
</ul>
</li>
<li><a href="#writing-tcp-servers-and-clients">Writing TCP Servers and Clients</a><ul>
<li><a href="#net-server">Net Server</a><ul>
<li><a href="#creating-a-net-server">Creating a Net Server</a></li>
<li><a href="#start-the-server-listening">Start the Server Listening</a></li>
<li><a href="#getting-notified-of-incoming-connections">Getting Notified of Incoming Connections</a></li>
<li><a href="#closing-a-net-server">Closing a Net Server</a></li>
<li><a href="#netserver-properties">NetServer Properties</a></li>
<li><a href="#handling-data">Handling Data</a><ul>
<li><a href="#reading-data-from-the-socket">Reading Data from the Socket</a></li>
<li><a href="#writing-data-to-a-socket">Writing Data to a Socket</a></li>
</ul>
</li>
<li><a href="#socket-remote-address">Socket Remote Address</a></li>
<li><a href="#socket-local-address">Socket Local Address</a></li>
<li><a href="#closing-a-socket">Closing a socket</a></li>
<li><a href="#closed-handler">Closed Handler</a></li>
<li><a href="#exception-handler">Exception handler</a></li>
<li><a href="#event-bus-write-handler">Event Bus Write Handler</a></li>
<li><a href="#read-and-write-streams">Read and Write Streams</a></li>
</ul>
</li>
<li><a href="#scaling-tcp-servers">Scaling TCP Servers</a></li>
<li><a href="#netclient">NetClient</a><ul>
<li><a href="#creating-a-net-client">Creating a Net Client</a></li>
<li><a href="#making-a-connection">Making a Connection</a></li>
<li><a href="#configuring-reconnection">Configuring Reconnection</a></li>
<li><a href="#netclient-properties">NetClient Properties</a></li>
</ul>
</li>
<li><a href="#ssl-servers">SSL Servers</a></li>
<li><a href="#ssl-clients">SSL Clients</a></li>
</ul>
</li>
<li><a href="#user-datagram-protocol-udp">User Datagram Protocol (UDP)</a><ul>
<li><a href="#creating-a-datagramsocket">Creating a DatagramSocket</a></li>
<li><a href="#sending-datagram-packets">Sending Datagram packets</a></li>
<li><a href="#receiving-datagram-packets">Receiving Datagram packets</a></li>
<li><a href="#multicast">Multicast</a><ul>
<li><a href="#sending-multicast-packets">Sending Multicast packets</a></li>
<li><a href="#receiving-multicast-packets">Receiving Multicast packets</a></li>
<li><a href="#unlisten-leave-a-multicast-group">Unlisten / leave a Multicast group</a></li>
<li><a href="#blocking-multicast">Blocking multicast</a></li>
</ul>
</li>
<li><a href="#datagramsocket-properties">DatagramSocket properties</a></li>
<li><a href="#datagramsocket-local-address">DatagramSocket Local Address</a></li>
<li><a href="#closing-a-datagramsocket">Closing a DatagramSocket</a></li>
</ul>
</li>
<li><a href="#flow-control-streams-and-pumps">Flow Control - Streams and Pumps</a><ul>
<li><a href="#readstream">ReadStream</a></li>
<li><a href="#writestream">WriteStream</a></li>
<li><a href="#pump">Pump</a></li>
</ul>
</li>
<li><a href="#writing-http-servers-and-clients">Writing HTTP Servers and Clients</a><ul>
<li><a href="#writing-http-servers">Writing HTTP servers</a><ul>
<li><a href="#creating-an-http-server">Creating an HTTP Server</a></li>
<li><a href="#start-the-server-listening_1">Start the Server Listening</a></li>
<li><a href="#getting-notified-of-incoming-requests">Getting Notified of Incoming Requests</a></li>
<li><a href="#handling-http-requests">Handling HTTP Requests</a><ul>
<li><a href="#request-method">Request Method</a></li>
<li><a href="#request-version">Request Version</a></li>
<li><a href="#request-uri">Request URI</a></li>
<li><a href="#request-path">Request Path</a></li>
<li><a href="#request-query">Request Query</a></li>
<li><a href="#request-headers">Request Headers</a></li>
<li><a href="#request-params">Request params</a></li>
<li><a href="#remote-address">Remote Address</a></li>
<li><a href="#absolute-uri">Absolute URI</a></li>
<li><a href="#reading-data-from-the-request-body">Reading Data from the Request Body</a></li>
<li><a href="#handling-multipart-form-uploads">Handling Multipart Form Uploads</a></li>
<li><a href="#handling-multipart-form-attributes">Handling Multipart Form Attributes</a></li>
</ul>
</li>
<li><a href="#http-server-responses">HTTP Server Responses</a></li>
<li><a href="#setting-status-code-and-message">Setting Status Code and Message</a><ul>
<li><a href="#writing-http-responses">Writing HTTP responses</a></li>
<li><a href="#ending-http-responses">Ending HTTP responses</a></li>
<li><a href="#closing-the-underlying-connection">Closing the underlying connection</a></li>
<li><a href="#response-headers">Response headers</a></li>
<li><a href="#chunked-http-responses-and-trailers">Chunked HTTP Responses and Trailers</a></li>
</ul>
</li>
<li><a href="#serving-files-directly-from-disk">Serving files directly from disk</a></li>
<li><a href="#pumping-responses">Pumping Responses</a></li>
<li><a href="#http-compression">HTTP Compression</a></li>
</ul>
</li>
<li><a href="#writing-http-clients">Writing HTTP Clients</a><ul>
<li><a href="#creating-an-http-client">Creating an HTTP Client</a></li>
<li><a href="#pooling-and-keep-alive">Pooling and Keep Alive</a></li>
<li><a href="#closing-the-client">Closing the client</a></li>
<li><a href="#making-requests">Making Requests</a><ul>
<li><a href="#handling-exceptions">Handling exceptions</a></li>
<li><a href="#writing-to-the-request-body">Writing to the request body</a></li>
<li><a href="#ending-http-requests">Ending HTTP requests</a></li>
<li><a href="#writing-request-headers">Writing Request Headers</a></li>
<li><a href="#request-timeouts">Request timeouts</a></li>
<li><a href="#http-chunked-requests">HTTP chunked requests</a></li>
</ul>
</li>
<li><a href="#http-client-responses">HTTP Client Responses</a><ul>
<li><a href="#reading-data-from-the-response-body">Reading Data from the Response Body</a></li>
<li><a href="#reading-cookies">Reading cookies</a></li>
</ul>
</li>
<li><a href="#100-continue-handling">100-Continue Handling</a></li>
<li><a href="#http-compression_1">HTTP Compression</a></li>
</ul>
</li>
<li><a href="#pumping-requests-and-responses">Pumping Requests and Responses</a></li>
<li><a href="#https-servers">HTTPS Servers</a></li>
<li><a href="#https-clients">HTTPS Clients</a></li>
<li><a href="#scaling-http-servers">Scaling HTTP servers</a></li>
</ul>
</li>
<li><a href="#routing-http-requests-with-pattern-matching">Routing HTTP requests with Pattern Matching</a><ul>
<li><a href="#specifying-matches">Specifying matches.</a></li>
<li><a href="#extracting-parameters-from-the-path">Extracting parameters from the path</a></li>
<li><a href="#extracting-params-using-regular-expressions">Extracting params using Regular Expressions</a></li>
<li><a href="#handling-requests-where-nothing-matches">Handling requests where nothing matches</a></li>
</ul>
</li>
<li><a href="#websockets">WebSockets</a><ul>
<li><a href="#websockets-on-the-server">WebSockets on the server</a><ul>
<li><a href="#reading-from-and-writing-to-websockets">Reading from and Writing to WebSockets</a></li>
<li><a href="#rejecting-websockets">Rejecting WebSockets</a></li>
<li><a href="#headers-on-the-websocket">Headers on the websocket</a></li>
</ul>
</li>
<li><a href="#websockets-on-the-http-client">WebSockets on the HTTP client</a></li>
<li><a href="#websockets-in-the-browser">WebSockets in the browser</a></li>
</ul>
</li>
<li><a href="#sockjs">SockJS</a><ul>
<li><a href="#sockjs-server">SockJS Server</a></li>
<li><a href="#reading-and-writing-data-from-a-sockjs-server">Reading and writing data from a SockJS server</a></li>
<li><a href="#sockjs-client">SockJS client</a></li>
</ul>
</li>
<li><a href="#sockjs-eventbus-bridge">SockJS - EventBus Bridge</a><ul>
<li><a href="#setting-up-the-bridge">Setting up the Bridge</a></li>
<li><a href="#using-the-event-bus-from-client-side-javascript">Using the Event Bus from client side JavaScript</a></li>
<li><a href="#securing-the-bridge">Securing the Bridge</a></li>
<li><a href="#messages-that-require-authorisation">Messages that require authorisation</a></li>
</ul>
</li>
<li><a href="#file-system">File System</a><ul>
<li><a href="#synchronous-forms">Synchronous forms</a></li>
<li><a href="#copy">copy</a></li>
<li><a href="#move">move</a></li>
<li><a href="#truncate">truncate</a></li>
<li><a href="#chmod">chmod</a></li>
<li><a href="#props">props</a></li>
<li><a href="#lprops">lprops</a></li>
<li><a href="#link">link</a></li>
<li><a href="#symlink">symlink</a></li>
<li><a href="#unlink">unlink</a></li>
<li><a href="#readsymlink">readSymLink</a></li>
<li><a href="#delete">delete</a></li>
<li><a href="#mkdir">mkdir</a></li>
<li><a href="#readdir">readDir</a></li>
<li><a href="#readfile">readFile</a></li>
<li><a href="#writefile">writeFile</a></li>
<li><a href="#createfile">createFile</a></li>
<li><a href="#exists">exists</a></li>
<li><a href="#fsprops">fsProps</a></li>
<li><a href="#open">open</a></li>
<li><a href="#asyncfile">AsyncFile</a><ul>
<li><a href="#random-access-writes">Random access writes</a></li>
<li><a href="#random-access-reads">Random access reads</a></li>
<li><a href="#flushing-data-to-underlying-storage">Flushing data to underlying storage.</a></li>
<li><a href="#using-asyncfile-as-readstream-and-writestream">Using AsyncFile as ReadStream and WriteStream</a></li>
<li><a href="#closing-an-asyncfile">Closing an AsyncFile</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#dns-client">DNS Client</a><ul>
<li><a href="#lookup">lookup</a></li>
<li><a href="#lookup4">lookup4</a></li>
<li><a href="#lookup6">lookup6</a></li>
<li><a href="#resolvea">resolveA</a></li>
<li><a href="#resolveaaaa">resolveAAAA</a></li>
<li><a href="#resolvecname">resolveCNAME</a></li>
<li><a href="#resolvemx">resolveMX</a></li>
<li><a href="#resolvetxt">resolveTXT</a></li>
<li><a href="#resolvens">resolveNS</a></li>
<li><a href="#resolvesrv">resolveSRV</a></li>
<li><a href="#resolveptr">resolvePTR</a></li>
<li><a href="#reverselookup">reverseLookup</a></li>
<li><a href="#error-handling">Error handling</a><ul>
<li><a href="#noerror">NOERROR</a></li>
<li><a href="#formerror">FORMERROR</a></li>
<li><a href="#servfail">SERVFAIL</a></li>
<li><a href="#nxdomain">NXDOMAIN</a></li>
<li><a href="#notimpl">NOTIMPL</a></li>
<li><a href="#refused">REFUSED</a></li>
<li><a href="#yxdomain">YXDOMAIN</a></li>
<li><a href="#yxrrset">YXRRSET</a></li>
<li><a href="#nxrrset">NXRRSET</a></li>
<li><a href="#notzone">NOTZONE</a></li>
<li><a href="#badver">BADVER</a></li>
<li><a href="#badsig">BADSIG</a></li>
<li><a href="#badkey">BADKEY</a></li>
<li><a href="#badtime">BADTIME</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<h1 id="writing-verticles">Writing Verticles</h1><br/>
<p>As was described in the <a href="manual.html#verticle">main manual</a>, a verticle is the execution unit of Vert.x.</p>
<p>To recap, Vert.x is a container which executes packages of code called Verticles, and it ensures that the code in the verticle is never executed concurrently by more than one thread. You can write your verticles in any of the languages that Vert.x supports, and Vert.x supports running many verticle instances concurrently in the same Vert.x instance.</p>
<p>All the code you write in a Vert.x application runs inside a Verticle instance.</p>
<p>For simple prototyping and trivial tasks you can write raw verticles and run them directly on the command line, but in most cases you will always wrap your verticles inside Vert.x <a href="mods_manual.html">modules</a>.</p>
<p>For now, let's try writing a simple raw verticle.</p>
<p>As an example we'll write a simple TCP echo server. The server just accepts connections and any data received by it is echoed back on the connection.</p>
<p>Copy the following into a text editor and save it as <code>Server.java</code></p>
<pre class="prettyprint">import org.vertx.java.core.Handler;
import org.vertx.java.core.net.NetSocket;
import org.vertx.java.core.streams.Pump;
import org.vertx.java.platform.Verticle;

public class Server extends Verticle {

  public void start() {
    vertx.createNetServer().connectHandler(new Handler&lt;NetSocket&gt;() {
      public void handle(final NetSocket socket) {
        Pump.createPump(socket, socket).start();
      }
    }).listen(1234);
  }
}
</pre>
<p>Now run it:</p>
<pre class="prettyprint">vertx run Server.java
</pre>
<p>The server will now be running. Connect to it using telnet:</p>
<pre class="prettyprint">telnet localhost 1234
</pre>
<p>And notice how data you send (and hit enter) is echoed back to you.</p>
<p>Congratulations! You've written your first verticle.</p>
<p>Notice how you didn't have to first compile the <code>.java</code> file to a <code>.class</code> file. Vert.x understands how to run <code>.java</code> files directly - internally doing the compilation on the fly. (It also supports running .class files too if you prefer)</p>
<p>Every Java verticle must extend the class <code>org.vertx.java.deploy.Verticle</code>. You must override the <code>start</code> method - this is called by Vert.x when the verticle is started.</p>
<p><em>In the rest of this manual we'll assume the code snippets are running inside a verticle.</em></p>
<h2 id="asynchronous-start">Asynchronous start</h2><br/>
<p>In some cases your Verticle has to do some other stuff asynchronously in its <code>start()</code> method, e.g. start other verticles, and the verticle shouldn't be considered started until those other actions are complete.</p>
<p>If this is the case for your verticle you can implement the asynchronous version of the <code>start()</code> method:</p>
<pre class="prettyprint">public void start(final Future&lt;Void&gt; startedResult) {
  // For example - deploy some other verticle
  container.deployVerticle("foo.js", new AsyncResultHandler&lt;String&gt;() {
    public void handle(AsyncResult&lt;String&gt; deployResult) {
      if (deployResult.succeeded()) {
        startedResult.setResult(null);
      } else {
        startedResult.setFailure(deployResult.cause());
      }
    }
  });
}
</pre>
<h2 id="verticle-clean-up">Verticle clean-up</h2><br/>
<p>Servers, clients, event bus handlers and timers will be automatically closed / cancelled when the verticle is stopped. However, if you have any other clean-up logic that you want to execute when the verticle is stopped, you can implement a <code>stop</code> method which will be called when the verticle is undeployed.</p>
<h2 id="the-container-object">The <code>container</code> object</h2><br/>
<p>Each verticle instance has a member variable called <code>container</code>. This represents the Verticle's view of the container in which it is running.</p>
<p>The container object contains methods for deploying and undeploying verticle and modules, and also allows config, environment variables and a logger to be accessed.</p>
<h2 id="the-vertx-object">The <code>vertx</code> object</h2><br/>
<p>Each verticle instance has a member variable called <code>vertx</code>. This provides access to the Vert.x core API. You'll use the Core API to do most things in Vert.x including TCP, HTTP, file system access, event bus, timers etc.</p>
<h2 id="getting-configuration-in-a-verticle">Getting Configuration in a Verticle</h2><br/>
<p>You can pass configuration to a module or verticle from the command line using the <code>-conf</code> option, for example:</p>
<pre class="prettyprint">vertx runmod com.mycompany~my-mod~1.0 -conf myconf.json
</pre>
<p>or for a raw verticle</p>
<pre class="prettyprint">vertx run foo.js -conf myconf.json
</pre>
<p>The argument to <code>-conf</code> is the name of a text file containing a valid JSON object.</p>
<p>That configuration is available inside your verticle by calling the <code>config()</code> method on the <code>container</code> member variable of the verticle:</p>
<pre class="prettyprint">JsonObject config = container.config();

System.out.println("Config is " + config);
</pre>
<p>The config returned is an instance of <code>org.vertx.java.core.json.JsonObject</code>, which is a class which represents JSON objects (unsurprisingly!). You can use this object to configure the verticle.</p>
<p>Allowing verticles to be configured in a consistent way like this allows configuration to be easily passed to them irrespective of the language that deploys the verticle.</p>
<h2 id="logging-from-a-verticle">Logging from a Verticle</h2><br/>
<p>Each verticle is given its own logger. To get a reference to it invoke the <code>logger()</code> method on the container instance:</p>
<pre class="prettyprint">Logger logger = container.logger();

logger.info("I am logging something");
</pre>
<p>The logger is an instance of the class <code>org.vertx.java.core.logging.Logger</code> and has the following methods;</p>
<ul>
<li>trace</li>
<li>debug</li>
<li>info</li>
<li>warn</li>
<li>error</li>
<li>fatal</li>
</ul>
<p>Which have the normal meanings you would expect.</p>
<p>The log files by default go in a file called <code>vertx.log</code> in the system temp directory. On my Linux box this is <code>\tmp</code>.</p>
<p>For more information on configuring logging, please see the <a href="manual.html#logging">main manual</a>.</p>
<h2 id="accessing-environment-variables-from-a-verticle">Accessing environment variables from a Verticle</h2><br/>
<p>You can access the map of environment variables from a Verticle with the <code>env()</code> method on the <code>container</code> object.</p>
<h2 id="causing-the-container-to-exit">Causing the container to exit</h2><br/>
<p>You can call the <code>exit()</code> method of the container to cause the Vert.x instance to make a clean shutdown.</p>
<h1 id="deploying-and-undeploying-verticles-programmatically">Deploying and Undeploying Verticles Programmatically</h1><br/>
<p>You can deploy and undeploy verticles programmatically from inside another verticle. Any verticles deployed this way will be able to see resources (classes, scripts, other files) of the main verticle.</p>
<h2 id="deploying-a-simple-verticle">Deploying a simple verticle</h2><br/>
<p>To deploy a verticle programmatically call the function <code>deployVerticle</code> on the <code>container</code> variable.</p>
<p>To deploy a single instance of a verticle :</p>
<pre class="prettyprint">container.deployVerticle(main);
</pre>
<p>Where <code>main</code> is the name of the Verticle (i.e. the name of the Java file or FQCN of the class).</p>
<p>See the chapter on <a href="manual.html#running-vertx">"running Vert.x"</a> in the main manual for a description of what a main is.</p>
<h2 id="deploying-worker-verticles">Deploying Worker Verticles</h2><br/>
<p>The <code>deployVerticle</code> method deploys standard (non worker) verticles. If you want to deploy worker verticles use the <code>deployWorkerVerticle</code> method. This method takes the same parameters as <code>deployVerticle</code> with the same meanings.</p>
<h2 id="deploying-a-module-programmatically">Deploying a module programmatically</h2><br/>
<p>You should use <code>deployModule</code> to deploy a module, for example:</p>
<pre class="prettyprint">container.deployModule("io.vertx~mod-mailer~2.0.0-beta1", config);
</pre>
<p>Would deploy an instance of the <code>io.vertx~mod-mailer~2.0.0-beta1</code> module with the specified configuration. Please see the <a href="">modules manual</a> for more information about modules.</p>
<h2 id="passing-configuration-to-a-verticle-programmatically">Passing configuration to a verticle programmatically</h2><br/>
<p>JSON configuration can be passed to a verticle that is deployed programmatically. Inside the deployed verticle the configuration is accessed with the <code>config()</code> method. For example:</p>
<pre class="prettyprint">JsonObject config = new JsonObject();
config.putString("foo", "wibble");
config.putBoolean("bar", false);
container.deployVerticle("foo.ChildVerticle", config);
</pre>
<p>Then, in <code>ChildVerticle</code> you can access the config via <code>config()</code> as previously explained.</p>
<h2 id="using-a-verticle-to-co-ordinate-loading-of-an-application">Using a Verticle to co-ordinate loading of an application</h2><br/>
<p>If you have an appplication that is composed of multiple verticles that all need to be started at application start-up, then you can use another verticle that maintains the application configuration and starts all the other verticles. You can think of this as your application starter verticle.</p>
<p>For example, you could create a verticle <code>AppStarter</code> as follows:</p>
<pre class="prettyprint">// Application config

JsonObject appConfig = container.config();

JsonObject verticle1Config = appConfig.getObject("verticle1_conf");
JsonObject verticle2Config = appConfig.getObject("verticle2_conf");
JsonObject verticle3Config = appConfig.getObject("verticle3_conf");
JsonObject verticle4Config = appConfig.getObject("verticle4_conf");
JsonObject verticle5Config = appConfig.getObject("verticle5_conf");

// Start the verticles that make up the app

container.deployVerticle("verticle1.js", verticle1Config);
container.deployVerticle("verticle2.rb", verticle2Config);
container.deployVerticle("foo.Verticle3", verticle3Config);
container.deployWorkerVerticle("foo.Verticle4", verticle4Config);
container.deployWorkerVerticle("verticle5.js", verticle5Config, 10);
</pre>
<p>Then create a file 'config.json" with the actual JSON config in it</p>
<pre class="prettyprint">{
    "verticle1_conf": {
        "foo": "wibble"
    },
    "verticle2_conf": {
        "age": 1234,
        "shoe_size": 12,
        "pi": 3.14159
    },
    "verticle3_conf": {
        "strange": true
    },
    "verticle4_conf": {
        "name": "george"
    },
    "verticle5_conf": {
        "tel_no": "123123123"
    }
}
</pre>
<p>Then set the <code>AppStarter</code> as the main of your module and then you can start your entire application by simply running:</p>
<pre class="prettyprint">vertx runmod com.mycompany~my-mod~1.0 -conf config.json
</pre>
<p>If your application is large and actually composed of multiple modules rather than verticles you can use the same technique.</p>
<p>More commonly you'd probably choose to write your starter verticle in a scripting language such as JavaScript, Groovy, Ruby or Python - these languages have much better JSON support than Java, so you can maintain the whole JSON config nicely in the starter verticle itself.</p>
<h2 id="specifying-number-of-instances">Specifying number of instances</h2><br/>
<p>By default, when you deploy a verticle only one instance of the verticle is deployed. Verticles instances are strictly single threaded so this means you will use at most one core on your server.</p>
<p>Vert.x scales by deploying many verticle instances concurrently.</p>
<p>If you want more than one instance of a particular verticle or module to be deployed, you can specify the number of instances as follows:</p>
<pre class="prettyprint">container.deployVerticle("foo.ChildVerticle", 10);
</pre>
<p>Or</p>
<pre class="prettyprint">container.deployModule("io.vertx~some-mod~1.0", 10);
</pre>
<p>The above examples would deploy 10 instances.</p>
<h2 id="getting-notified-when-deployment-is-complete">Getting Notified when Deployment is complete</h2><br/>
<p>The actual verticle deployment is asynchronous and might not complete until some time after the call to <code>deployVerticle</code> or <code>deployModule</code> has returned. If you want to be notified when the verticle has completed being deployed, you can pass a handler as the final argument to <code>deployVerticle</code> or <code>deployModule</code>:</p>
<pre class="prettyprint">container.deployVerticle("foo.ChildVerticle", new AsyncResultHandler&lt;String&gt;() {
    public void handle(AsyncResult&lt;String&gt; asyncResult) {
        if (asyncResult.succeeded()) {
            System.out.println("The verticle has been deployed, deployment ID is " + asyncResult.result());
        } else {
            asyncResult.cause().printStackTrace();
        }
    }
});
</pre>
<p>The handler will get passed an instance of <code>AsyncResult</code> when it completes. You can use the methods <code>succeeded()</code> and <code>failed()</code> on <code>AsyncResult</code> to see if the operation completed ok.</p>
<p>The method <code>result()</code> provides the result of the async operation (if any) which in this case is the deployment ID - you will need this if you need to subsequently undeploy the verticle / module.</p>
<p>The method <code>cause()</code> provides the <code>Throwable</code> if the action failed.</p>
<h2 id="undeploying-a-verticle-or-module">Undeploying a Verticle or Module</h2><br/>
<p>Any verticles or modules that you deploy programmatically from within a verticle, and all of their children are automatically undeployed when the parent verticle is undeployed, so in many cases you will not need to undeploy a verticle manually, however if you do need to do this, it can be done by calling the method <code>undeployVerticle</code> or <code>undeployModule</code> passing in the deployment id.</p>
<pre class="prettyprint">container.undeployVerticle(deploymentID);
</pre>
<p>You can also provide a handler to the undeploy method if you want to be informed when undeployment is complete.</p>
<h1 id="scaling-your-application">Scaling your application</h1><br/>
<p>A verticle instance is almost always single threaded (the only exception is multi-threaded worker verticles which are an advanced feature), this means a single instance can at most utilise one core of your server.</p>
<p>In order to scale across cores you need to deploy more verticle instances. The exact numbers depend on your application - how many verticles there are and of what type.</p>
<p>You can deploy more verticle instances programmatically or on the command line when deploying your module using the <code>-instances</code> command line option.</p>
<p><a id="event-bus"> </a></p>
<h1 id="the-event-bus">The Event Bus</h1><br/>
<p>The event bus is the nervous system of Vert.x.</p>
<p>It allows verticles to communicate with each other irrespective of what language they are written in, and whether they're in the same Vert.x instance, or in a different Vert.x instance.</p>
<p>It even allows client side JavaScript running in a browser to communicate on the same event bus. (More on that later).</p>
<p>The event bus forms a distributed peer-to-peer messaging system spanning multiple server nodes and multiple browsers.</p>
<p>The event bus API is incredibly simple. It basically involves registering handlers, unregistering handlers and sending and publishing messages.</p>
<p>First some theory:</p>
<h2 id="the-theory">The Theory</h2><br/>
<h3 id="addressing">Addressing</h3><br/>
<p>Messages are sent on the event bus to an <em>address</em>.</p>
<p>Vert.x doesn't bother with any fancy addressing schemes. In Vert.x an address is simply a string, any string is valid. However it is wise to use some kind of scheme, e.g. using periods to demarcate a namespace.</p>
<p>Some examples of valid addresses are <code>europe.news.feed1</code>, <code>acme.games.pacman</code>, <code>sausages</code>, and <code>X</code>.</p>
<h3 id="handlers">Handlers</h3><br/>
<p>A handler is a thing that receives messages from the bus. You register a handler at an address.</p>
<p>Many different handlers from the same or different verticles can be registered at the same address. A single handler can be registered by the verticle at many different addresses.</p>
<h3 id="publish-subscribe-messaging">Publish / subscribe messaging</h3><br/>
<p>The event bus supports <em>publishing</em> messages. Messages are published to an address. Publishing means delivering the message to all handlers that are registered at that address. This is the familiar <em>publish/subscribe</em> messaging pattern.</p>
<h3 id="point-to-point-and-request-response-messaging">Point to point and Request-Response messaging</h3><br/>
<p>The event bus supports <em>point to point</em> messaging. Messages are sent to an address. Vert.x will then route it to just one of the handlers registered at that address. If there is more than one handler registered at the address, one will be chosen using a non-strict round-robin algorithm.</p>
<p>With point to point messaging, an optional reply handler can be specified when sending the message. When a message is received by a recipient, and has been handled, the recipient can optionally decide to reply to the message. If they do so that reply handler will be called.</p>
<p>When the reply is received back at the sender, it too can be replied to. This can be repeated ad-infinitum, and allows a dialog to be set-up between two different verticles. This is a common messaging pattern called the <em>Request-Response</em> pattern.</p>
<h3 id="transient">Transient</h3><br/>
<p><em>All messages in the event bus are transient, and in case of failure of all or parts of the event bus, there is a possibility messages will be lost. If your application cares about lost messages, you should code your handlers to be idempotent, and your senders to retry after recovery.</em></p>
<p>If you want to persist your messages you can use a persistent work queue module for that.</p>
<h3 id="types-of-messages">Types of messages</h3><br/>
<p>Messages that you send on the event bus can be as simple as a string, a number or a boolean. You can also send Vert.x buffers or JSON messages.</p>
<p>It's highly recommended you use JSON messages to communicate between verticles. JSON is easy to create and parse in all the languages that Vert.x supports.</p>
<h2 id="event-bus-api">Event Bus API</h2><br/>
<p>Let's jump into the API.</p>
<h3 id="registering-and-unregistering-handlers">Registering and Unregistering Handlers</h3><br/>
<p>To set a message handler on the address <code>test.address</code>, you do something like the following:</p>
<pre class="prettyprint">EventBus eb = vertx.eventBus();

Handler&lt;Message&gt; myHandler = new Handler&lt;Message&gt;() {
    public void handle(Message message) {
        System.out.println("I received a message " + message.body);
    }
};

eb.registerHandler("test.address", myHandler);
</pre>
<p>It's as simple as that. The handler will then receive any messages sent to that address.</p>
<p>The class <code>Message</code> is a generic type and specific Message types include <code>Message&lt;Boolean&gt;</code>, <code>Message&lt;Buffer&gt;</code>, <code>Message&lt;byte[]&gt;</code>, <code>Message&lt;Byte&gt;</code>, <code>Message&lt;Character&gt;</code>, <code>Message&lt;Double&gt;</code>, <code>Message&lt;Float&gt;</code>, <code>Message&lt;Integer&gt;</code>, <code>Message&lt;JsonObject&gt;</code>, <code>Message&lt;JsonArray&gt;</code>, <code>Message&lt;Long&gt;</code>, <code>Message&lt;Short&gt;</code> and <code>Message&lt;String&gt;</code>.</p>
<p>If you know you'll always be receiving messages of a particular type you can use the specific type in your handler, e.g:</p>
<pre class="prettyprint">Handler&lt;Message&lt;String&gt;&gt; myHandler = new Handler&lt;Message&lt;String&gt;&gt;() {
    public void handle(Message&lt;String&gt; message) {
        String body = message.body;
    }
};
</pre>
<p>The return value of <code>registerHandler</code> is the Event Bus itself, i.e. we provide a <em>fluent</em> API so you can chain multiple calls together.</p>
<p>When you register a handler on an address and you're in a cluster it can take some time for the knowledge of that new handler to be propagated across the entire cluster. If you want to be notified when that has completed you can optionally specify another handler to the <code>registerHandler</code> method as the third argument. This handler will then be called once the information has reached all nodes of the cluster. E.g. :</p>
<pre class="prettyprint">eb.registerHandler("test.address", myHandler, new AsyncResultHandler&lt;Void&gt;() {
    public void handle(AsyncResult&lt;Void&gt; asyncResult) {
        System.out.println("The handler has been registered across the cluster ok? " + asyncResult.succeeded());
    }
});
</pre>
<p>To unregister a handler it's just as straightforward. You simply call <code>unregisterHandler</code> passing in the address and the handler:</p>
<pre class="prettyprint">eb.unregisterHandler("test.address", myHandler);
</pre>
<p>A single handler can be registered multiple times on the same, or different, addresses so in order to identify it uniquely you have to specify both the address and the handler.</p>
<p>As with registering, when you unregister a handler and you're in a cluster it can also take some time for the knowledge of that unregistration to be propagated across the entire to cluster. If you want to be notified when that has completed you can optionally specify another function to the registerHandler as the third argument. E.g. :</p>
<pre class="prettyprint">eb.unregisterHandler("test.address", myHandler, new AsyncResultHandler&lt;Void&gt;() {
    public void handle(AsyncResult&lt;Void&gt; asyncResult) {
        System.out.println("The handler has been unregistered across the cluster ok? " + asyncResult.succeeded());
    }
});
</pre>
<p>If you want your handler to live for the full lifetime of your verticle there is no need to unregister it explicitly - Vert.x will automatically unregister any handlers when the verticle is stopped.</p>
<h3 id="publishing-messages">Publishing messages</h3><br/>
<p>Publishing a message is also trivially easy. Just publish it specifying the address, for example:</p>
<pre class="prettyprint">eb.publish("test.address", "hello world");
</pre>
<p>That message will then be delivered to all handlers registered against the address "test.address".</p>
<h3 id="sending-messages">Sending messages</h3><br/>
<p>Sending a message will result in only one handler registered at the address receiving the message. This is the point to point messaging pattern. The handler is chosen in a non strict round-robin fashion.</p>
<pre class="prettyprint">eb.send("test.address", "hello world");
</pre>
<h3 id="replying-to-messages">Replying to messages</h3><br/>
<p>Sometimes after you send a message you want to receive a reply from the recipient. This is known as the <em>request-response pattern</em>.</p>
<p>To do this you send a message, and specify a reply handler as the third argument. When the receiver receives the message they can reply to it by calling the <code>reply</code> method on the message.. When this method is invoked it causes a reply to be sent back to the sender where the reply handler is invoked. An example will make this clear:</p>
<p>The receiver:</p>
<pre class="prettyprint">Handler&lt;Message&lt;String&gt;&gt; myHandler = new Handler&lt;Message&lt;String&gt;&gt;() {
    public void handle(Message&lt;String&gt; message) {
        System.out.println("I received a message " + message.body);

        // Do some stuff

        // Now reply to it

        message.reply("This is a reply");
    }
};

eb.registerHandler("test.address", myHandler);
</pre>
<p>The sender:</p>
<pre class="prettyprint">eb.send("test.address", "This is a message", new Handler&lt;Message&lt;String&gt;&gt;() {
    public void handle(Message&lt;String&gt; message) {
        System.out.println("I received a reply " + message.body);
    }
});
</pre>
<p>It is legal also to send an empty reply or a null reply.</p>
<p>The replies themselves can also be replied to so you can create a dialog between two different verticles consisting of multiple rounds.</p>
<h4 id="specifying-timeouts-for-replies">Specifying timeouts for replies</h4><br/>
<p>If you send a message specifying a reply handler, and the reply never comes, then, by default, you'll be left with a handler that never gets unregistered.</p>
<p>To remedy this you can also specify a <code>Handler&lt;AsyncResult&lt;Message&gt;&gt;</code> as a reply handler and a timeout in ms. If a reply is received before timeout your handler will be called with an <code>AsyncResult</code> containing the message, but if no reply is received before timeout, the handler will be automatically unregistered and your handler will be called with a failed result so you can deal with it in your code.</p>
<p>Here's an example:</p>
<pre class="prettyprint">eb.sendWithTimeout("test.address", "This is a message", 1000, new Handler&lt;AsyncResult&lt;Message&lt;String&gt;&gt;&gt;() {
    public void handle(AsyncResult&lt;Message&lt;String&gt;&gt; result) {
        if (result.succeeded()) {
            System.out.println("I received a reply " + message.body);
        } else {

            System.err.println("No reply was received before the 1 second timeout!");
        }
    }
});
</pre>
<p>If the send times out, the exception it is available with the <code>cause()</code> method of the <code>AsyncResult</code> is of type <code>ReplyException</code>. The return value <code>failureType()</code> on the <code>ReplyException</code> instance is <code>ReplyFailure.TIMEOUT</code>.</p>
<p>You can also set a default timeout on the event bus itself - this timeout will be used if you are using the <code>send(...)</code> method on the event bus to send messages with a reply handler. The default value of the default timeout is <code>-1</code> which means that reply handlers will never timeout (this is for backward compatibility reasons with earlier versions of Vert.x).</p>
<pre class="prettyprint">eb.setDefaultReplyTimeout(5000);

eb.send("test.address", "This is a message", new Handler&lt;Message&lt;String&gt;&gt;() {
    public void handle(Message&lt;String&gt; message) {
        System.out.println("I received a reply before the timeout of 5 seconds");
    }
});
</pre>
<p>When replying to messages you can also provide a timeout and a <code>Handler&lt;AsyncResult&lt;Message&gt;&gt;</code> to get replies to the replies within a timeout. The API used is similar to before:</p>
<pre class="prettyprint">message.replyWithTimeout("This is a reply", 1000, new Handler&lt;AsyncResult&lt;Message&lt;String&gt;&gt;&gt;() {
    public void handle(AsyncResult&lt;Message&lt;String&gt;&gt; result) {
        if (result.succeeded()) {
            System.out.println("I received a reply to the reply" + message.body);
        } else {
            System.err.println("No reply to the reply was received before the 1 second timeout!");
        }
    }
});
</pre>
<h4 id="getting-notified-of-reply-failures">Getting notified of reply failures</h4><br/>
<p>If you send a message with a timeout and result handler, and there are no handlers available to send the message to, the handler will be called with a failed <code>AsyncResult</code> where the <code>cause()</code> is a <code>ReplyException</code>. The return value <code>failureType()</code> on the <code>ReplyException</code> instance is <code>ReplyFailure.NO_HANDLERS</code>.</p>
<p>If you send a message with a timeout and result handler, and the recipent of the message responds by calling <code>Message.fail(..)</code>, the handler will be called with a failed <code>AsyncResult</code> where the <code>cause()</code> is a <code>ReplyException</code>. The return value <code>failureType()</code> on the <code>ReplyException</code> instance is <code>ReplyFailure.RECIPIENT_FAILURE</code>.</p>
<p>For example</p>
<pre class="prettyprint">eb.registerHandler("test.address", new Handler&lt;Message&lt;String&gt;&gt;() {
    public void handle(Message&lt;String&gt; message) {
        message.fail(123, "Not enough aardvarks");
    }
});

eb.sendWithTimeout("test.address", "This is a message", 1000, new Handler&lt;AsyncResult&lt;Message&lt;String&gt;&gt;&gt;() {
    public void handle(AsyncResult&lt;Message&lt;String&gt;&gt; result) {
        if (result.succeeded()) {
            System.out.println("I received a reply " + message.body);
        } else {
            ReplyException ex = (ReplyException)result.cause();
            System.err.println("Failure type: " + ex.failureType();
            System.err.println("Failure code: " + ex.failureCode();
            System.err.println("Failure message: " + ex.message();
        }
    }
});
</pre>
<h3 id="message-types">Message types</h3><br/>
<p>The message you send can be any of the following types (or their matching boxed type):</p>
<ul>
<li>boolean</li>
<li>byte[]</li>
<li>byte</li>
<li>char</li>
<li>double</li>
<li>float</li>
<li>int</li>
<li>long</li>
<li>short</li>
<li>java.lang.String</li>
<li>org.vertx.java.core.json.JsonObject</li>
<li>org.vertx.java.core.json.JsonArray</li>
<li>org.vertx.java.core.buffer.Buffer</li>
</ul>
<p>Vert.x buffers and JSON objects and arrays are copied before delivery if they are delivered in the same JVM, so different verticles can't access the exact same object instance which could lead to race conditions.</p>
<p>Here are some more examples:</p>
<p>Send some numbers:</p>
<pre class="prettyprint">eb.send("test.address", 1234);
eb.send("test.address", 3.14159);
</pre>
<p>Send a boolean:</p>
<pre class="prettyprint">eb.send("test.address", true);
</pre>
<p>Send a JSON object:</p>
<pre class="prettyprint">JsonObject obj = new JsonObject();
obj.putString("foo", "wibble");
eb.send("test.address", obj);
</pre>
<p>Null messages can also be sent:</p>
<pre class="prettyprint">eb.send("test.address", null);
</pre>
<p>It's a good convention to have your verticles communicating using JSON - this is because JSON is easy to generate and parse for all the languages that Vert.x supports.</p>
<h2 id="distributed-event-bus">Distributed event bus</h2><br/>
<p>To make each Vert.x instance on your network participate on the same event bus, start each Vert.x instance with the <code>-cluster</code> command line switch.</p>
<p>See the chapter in the main manual on <a href=""><em>running Vert.x</em></a> for more information on this.</p>
<p>Once you've done that, any Vert.x instances started in cluster mode will merge to form a distributed event bus.</p>
<h1 id="shared-data">Shared Data</h1><br/>
<p>Sometimes it makes sense to allow different verticles instances to share data in a safe way. Vert.x allows simple <code>java.util.concurrent.ConcurrentMap</code> and <code>java.util.Set</code> data structures to be shared between verticles.</p>
<p>There is a caveat: To prevent issues due to mutable data, Vert.x only allows simple immutable types such as number, boolean and string or Buffer to be used in shared data. With a Buffer, it is automatically copied when retrieved from the shared data, so different verticle instances never see the same object instance.</p>
<p>Currently data can only be shared between verticles in the <em>same Vert.x instance</em>. In later versions of Vert.x we aim to extend this to allow data to be shared by all Vert.x instances in the cluster.</p>
<h2 id="shared-maps">Shared Maps</h2><br/>
<p>To use a shared map to share data between verticles first we get a reference to the map, and then use it like any other instance of <code>java.util.concurrent.ConcurrentMap</code></p>
<pre class="prettyprint">ConcurrentMap&lt;String, Integer&gt; map = vertx.sharedData().getMap("demo.mymap");

map.put("some-key", 123);
</pre>
<p>And then, in a different verticle you can access it:</p>
<pre class="prettyprint">ConcurrentMap&lt;String, Integer&gt; map = vertx.sharedData().getMap("demo.mymap");

// etc
</pre>
<h2 id="shared-sets">Shared Sets</h2><br/>
<p>To use a shared set to share data between verticles first we get a reference to the set.</p>
<pre class="prettyprint">Set&lt;String&gt; set = vertx.sharedData().getSet("demo.myset");

set.add("some-value");
</pre>
<p>And then, in a different verticle:</p>
<pre class="prettyprint">Set&lt;String&gt; set = vertx.sharedData().getSet("demo.myset");

// etc
</pre>
<h1 id="buffers">Buffers</h1><br/>
<p>Most data in Vert.x is shuffled around using instances of <code>org.vertx.java.core.buffer.Buffer</code>.</p>
<p>A Buffer represents a sequence of zero or more bytes that can be written to or read from, and which expands automatically as necessary to accomodate any bytes written to it. You can perhaps think of a buffer as smart byte array.</p>
<h2 id="creating-buffers">Creating Buffers</h2><br/>
<p>Create a new empty buffer:</p>
<pre class="prettyprint">Buffer buff = new Buffer();
</pre>
<p>Create a buffer from a String. The String will be encoded in the buffer using UTF-8.</p>
<pre class="prettyprint">Buffer buff = new Buffer("some-string");
</pre>
<p>Create a buffer from a String: The String will be encoded using the specified encoding, e.g:</p>
<pre class="prettyprint">Buffer buff = new Buffer("some-string", "UTF-16");
</pre>
<p>Create a buffer from a byte[]</p>
<pre class="prettyprint">byte[] bytes = new byte[] { ... };
new Buffer(bytes);
</pre>
<p>Create a buffer with an initial size hint. If you know your buffer will have a certain amount of data written to it you can create the buffer and specify this size. This makes the buffer initially allocate that much memory and is more efficient than the buffer automatically resizing multiple times as data is written to it.</p>
<p>Note that buffers created this way <em>are empty</em>. It does not create a buffer filled with zeros up to the specified size.</p>
<pre class="prettyprint">Buffer buff = new Buffer(100000);
</pre>
<h2 id="writing-to-a-buffer">Writing to a Buffer</h2><br/>
<p>There are two ways to write to a buffer: appending, and random access. In either case buffers will always expand automatically to encompass the bytes. It's not possible to get an <code>IndexOutOfBoundsException</code> with a buffer.</p>
<h3 id="appending-to-a-buffer">Appending to a Buffer</h3><br/>
<p>To append to a buffer, you use the <code>appendXXX</code> methods. Append methods exist for appending other buffers, byte[], String and all primitive types.</p>
<p>The return value of the <code>appendXXX</code> methods is the buffer itself, so these can be chained:</p>
<pre class="prettyprint">Buffer buff = new Buffer();

buff.appendInt(123).appendString("hello\n");

socket.write(buff);
</pre>
<h3 id="random-access-buffer-writes">Random access buffer writes</h3><br/>
<p>You can also write into the buffer at a specific index, by using the <code>setXXX</code> methods. Set methods exist for other buffers, byte[], String and all primitive types. All the set methods take an index as the first argument - this represents the position in the buffer where to start writing the data.</p>
<p>The buffer will always expand as necessary to accomodate the data.</p>
<pre class="prettyprint">Buffer buff = new Buffer();

buff.setInt(1000, 123);
buff.setBytes(0, "hello");
</pre>
<h2 id="reading-from-a-buffer">Reading from a Buffer</h2><br/>
<p>Data is read from a buffer using the <code>getXXX</code> methods. Get methods exist for byte[], String and all primitive types. The first argument to these methods is an index in the buffer from where to get the data.</p>
<pre class="prettyprint">Buffer buff = ...;
for (int i = 0; i &lt; buff.length(); i += 4) {
    System.out.println("int value at " + i + " is " + buff.getInt(i));
}
</pre>
<h2 id="other-buffer-methods">Other buffer methods:</h2><br/>
<ul>
<li><code>length()</code>. To obtain the length of the buffer. The length of a buffer is the index of the byte in the buffer with the largest index + 1.</li>
<li><code>copy()</code>. Copy the entire buffer</li>
</ul>
<p>See the JavaDoc for more detailed method level documentation.</p>
<h1 id="json">JSON</h1><br/>
<p>Whereas JavaScript has first class support for JSON, and Ruby has Hash literals which make representing JSON easy within code, things aren't so easy in Java.</p>
<p>For this reason, if you want to use JSON from within your Java verticles, we provide some simple JSON classes which represent a JSON object and a JSON array. These classes provide methods for setting and getting all types supported in JSON on an object or array.</p>
<p>A JSON object is represented by instances of <code>org.vertx.java.core.json.JsonObject</code>. A JSON array is represented by instances of <code>org.vertx.java.core.json.JsonArray</code>.</p>
<p>A usage example would be using a Java verticle to send or receive JSON messages from the event bus.</p>
<pre class="prettyprint">EventBus eb = vertx.eventBus();

JsonObject obj = new JsonObject().putString("foo", "wibble")
                                 .putNumber("age", 1000);

eb.send("some-address", obj);


// ....
// And in a handler somewhere:

public void handle(Message&lt;JsonObject&gt; message) {
    System.out.println("foo is " + message.body.getString("foo");
    System.out.println("age is " + message.body.getNumber("age");
}
</pre>
<p>Methods also existing for converting this objects to and from their JSON serialized forms.</p>
<p>Please see the JavaDoc for the full Java Json API.</p>
<h1 id="delayed-and-periodic-tasks">Delayed and Periodic Tasks</h1><br/>
<p>It's very common in Vert.x to want to perform an action after a delay, or periodically.</p>
<p>In standard verticles you can't just make the thread sleep to introduce a delay, as that will block the event loop thread.</p>
<p>Instead you use Vert.x timers. Timers can be <em>one-shot</em> or <em>periodic</em>. We'll discuss both</p>
<h2 id="one-shot-timers">One-shot Timers</h2><br/>
<p>A one shot timer calls an event handler after a certain delay, expressed in milliseconds.</p>
<p>To set a timer to fire once you use the <code>setTimer</code> method passing in the delay and a handler</p>
<pre class="prettyprint">long timerID = vertx.setTimer(1000, new Handler&lt;Long&gt;() {
    public void handle(Long timerID) {
        log.info("And one second later this is printed");
    }
});

log.info("First this is printed");
</pre>
<p>The return value is a unique timer id which can later be used to cancel the timer. The handler is also passed the timer id.</p>
<h2 id="periodic-timers">Periodic Timers</h2><br/>
<p>You can also set a timer to fire periodically by using the <code>setPeriodic</code> method. There will be an initial delay equal to the period. The return value of <code>setPeriodic</code> is a unique timer id (long). This can be later used if the timer needs to be cancelled. The argument passed into the timer event handler is also the unique timer id:</p>
<pre class="prettyprint">long timerID = vertx.setPeriodic(1000, new Handler&lt;Long&gt;() {
    public void handle(Long timerID) {
        log.info("And every second this is printed");
    }
});

log.info("First this is printed");
</pre>
<h2 id="cancelling-timers">Cancelling timers</h2><br/>
<p>To cancel a periodic timer, call the <code>cancelTimer</code> method specifying the timer id. For example:</p>
<pre class="prettyprint">long timerID = vertx.setPeriodic(1000, new Handler&lt;Long&gt;() {
    public void handle(Long timerID) {
    }
});

// And immediately cancel it

vertx.cancelTimer(timerID);
</pre>
<p>Or you can cancel it from inside the event handler. The following example cancels the timer after it has fired 10 times.</p>
<pre class="prettyprint">long timerID = vertx.setPeriodic(1000, new Handler&lt;Long&gt;() {
    int count;
    public void handle(Long timerID) {
        log.info("In event handler " + count);
        if (++count == 10) {
            vertx.cancelTimer(timerID);
        }
    }
});
</pre>
<h1 id="writing-tcp-servers-and-clients">Writing TCP Servers and Clients</h1><br/>
<p>Creating TCP servers and clients is very easy with Vert.x.</p>
<h2 id="net-server">Net Server</h2><br/>
<h3 id="creating-a-net-server">Creating a Net Server</h3><br/>
<p>To create a TCP server you call the <code>createNetServer</code> method on your <code>vertx</code> instance.</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();
</pre>
<h3 id="start-the-server-listening">Start the Server Listening</h3><br/>
<p>To tell that server to listen for connections we do:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.listen(1234, "myhost");
</pre>
<p>The first parameter to <code>listen</code> is the port. A wildcard port of <code>0</code> can be specified which means a random available port will be chosen to actually listen at. Once the server has completed listening you can then call the <code>port()</code> method of the server to find out the real port it is using.</p>
<p>The second parameter is the hostname or ip address. If it is omitted it will default to <code>0.0.0.0</code> which means it will listen at all available interfaces.</p>
<p>The actual bind is asynchronous so the server might not actually be listening until some time <em>after</em> the call to listen has returned. If you want to be notified when the server is actually listening you can provide a handler to the <code>listen</code> call. For example:</p>
<pre class="prettyprint">server.listen(1234, "myhost", new AsyncResultHandler&lt;Void&gt;() {
    public void handle(AsyncResult&lt;NetServer&gt; asyncResult) {
        log.info("Listen succeeded? " + asyncResult.succeeded());
    }
});
</pre>
<h3 id="getting-notified-of-incoming-connections">Getting Notified of Incoming Connections</h3><br/>
<p>To be notified when a connection occurs we need to call the <code>connectHandler</code> method of the server, passing in a handler. The handler will then be called when a connection is made:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(NetSocket sock) {
        log.info("A client has connected!");
    }
});

server.listen(1234, "localhost");
</pre>
<p>That's a bit more interesting. Now it displays 'A client has connected!' every time a client connects.</p>
<p>The return value of the <code>connectHandler</code> method is the server itself, so multiple invocations can be chained together. That means we can rewrite the above as:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(NetSocket sock) {
        log.info("A client has connected!");
    }
}).listen(1234, "localhost");
</pre>
<p>or</p>
<pre class="prettyprint">vertx.createNetServer().connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(NetSocket sock) {
        log.info("A client has connected!");
    }
}).listen(1234, "localhost");
</pre>
<p>This is a common pattern throughout the Vert.x API.</p>
<h3 id="closing-a-net-server">Closing a Net Server</h3><br/>
<p>To close a net server just call the <code>close</code> function.</p>
<pre class="prettyprint">server.close();
</pre>
<p>The close is actually asynchronous and might not complete until some time after the <code>close</code> method has returned. If you want to be notified when the actual close has completed then you can pass in a handler to the <code>close</code> method.</p>
<p>This handler will then be called when the close has fully completed.</p>
<pre class="prettyprint">server.close(new AsyncResultHandler&lt;Void&gt;() {
    public void handle(AsyncResult&lt;Void&gt; asyncResult) {
        log.info("Close succeeded? " + asyncResult.succeeded());
    }
});
</pre>
<p>If you want your net server to last the entire lifetime of your verticle, you don't need to call <code>close</code> explicitly, the Vert.x container will automatically close any servers that you created when the verticle is undeployed.</p>
<h3 id="netserver-properties">NetServer Properties</h3><br/>
<p>NetServer has a set of properties you can set which affect its behaviour. Firstly there are bunch of properties used to tweak the TCP parameters, in most cases you won't need to set these:</p>
<ul>
<li>
<p><code>setTCPNoDelay(tcpNoDelay)</code> If true then <a href="http://en.wikipedia.org/wiki/Nagle's_algorithm">Nagle's Algorithm</a> is disabled. If false then it is enabled.</p>
</li>
<li>
<p><code>setSendBufferSize(size)</code> Sets the TCP send buffer size in bytes.</p>
</li>
<li>
<p><code>setReceiveBufferSize(size)</code> Sets the TCP receive buffer size in bytes.</p>
</li>
<li>
<p><code>setTCPKeepAlive(keepAlive)</code> if <code>keepAlive</code> is true then <a href="http://en.wikipedia.org/wiki/Keepalive#TCP_keepalive">TCP keep alive</a> is enabled, if false it is disabled.</p>
</li>
<li>
<p><code>setReuseAddress(reuse)</code> if <code>reuse</code> is true then addresses in TIME_WAIT state can be reused after they have been closed.</p>
</li>
<li>
<p><code>setSoLinger(linger)</code></p>
</li>
<li>
<p><code>setTrafficClass(trafficClass)</code></p>
</li>
</ul>
<p>NetServer has a further set of properties which are used to configure SSL. We'll discuss those later on.</p>
<h3 id="handling-data">Handling Data</h3><br/>
<p>So far we have seen how to create a NetServer, and accept incoming connections, but not how to do anything interesting with the connections. Let's remedy that now.</p>
<p>When a connection is made, the connect handler is called passing in an instance of <code>NetSocket</code>. This is a socket-like interface to the actual connection, and allows you to read and write data as well as do various other things like close the socket.</p>
<h4 id="reading-data-from-the-socket">Reading Data from the Socket</h4><br/>
<p>To read data from the socket you need to set the <code>dataHandler</code> on the socket. This handler will be called with an instance of <code>org.vertx.java.core.buffer.Buffer</code> every time data is received on the socket. You could try the following code and telnet to it to send some data:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(NetSocket sock) {
        sock.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer buffer) {
                log.info("I received " + buffer.length() + " bytes of data");
            }
        });
    }
}).listen(1234, "localhost");
</pre>
<h4 id="writing-data-to-a-socket">Writing Data to a Socket</h4><br/>
<p>To write data to a socket, you invoke the <code>write</code> function. This function can be invoked in a few ways:</p>
<p>With a single buffer:</p>
<pre class="prettyprint">Buffer myBuffer = new Buffer(...);
sock.write(myBuffer);
</pre>
<p>A string. In this case the string will encoded using UTF-8 and the result written to the wire.</p>
<pre class="prettyprint">sock.write("hello");
</pre>
<p>A string and an encoding. In this case the string will encoded using the specified encoding and the result written to the wire.</p>
<pre class="prettyprint">sock.write("hello", "UTF-16");
</pre>
<p>The <code>write</code> function is asynchronous and always returns immediately after the write has been queued.</p>
<p>Let's put it all together.</p>
<p>Here's an example of a simple TCP echo server which simply writes back (echoes) everything that it receives on the socket:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(final NetSocket sock) {
        sock.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer buffer) {
                sock.write(buffer);
            }
        });
    }
}).listen(1234, "localhost");
</pre>
<h3 id="socket-remote-address">Socket Remote Address</h3><br/>
<p>You can find out the remote address of the socket (i.e. the address of the other side of the TCP IP connection) by calling <code>remoteAddress()</code>.</p>
<h3 id="socket-local-address">Socket Local Address</h3><br/>
<p>You can find out the local address of the socket (i.e. the address of this side of the TCP IP connection) by calling <code>localAddress()</code>.</p>
<h3 id="closing-a-socket">Closing a socket</h3><br/>
<p>You can close a socket by invoking the <code>close</code> method. This will close the underlying TCP connection.</p>
<h3 id="closed-handler">Closed Handler</h3><br/>
<p>If you want to be notified when a socket is closed, you can set the `closedHandler':</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(final NetSocket sock) {
        sock.closedHandler(new VoidHandler() {
            public void handle() {
                log.info("The socket is now closed");
            }
        });
    }
}).listen(1234, "localhost");
</pre>
<p>The closed handler will be called irrespective of whether the close was initiated by the client or server.</p>
<h3 id="exception-handler">Exception handler</h3><br/>
<p>You can set an exception handler on the socket that will be called if an exception occurs asynchronously on the connection:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(final NetSocket sock) {
        sock.exceptionHandler(new Handler&lt;Throwable&gt;() {
            public void handle(Throwable t) {
                log.info("Oops, something went wrong", t);
            }
        });
    }
}).listen(1234, "localhost");
</pre>
<h3 id="event-bus-write-handler">Event Bus Write Handler</h3><br/>
<p>Every NetSocket automatically registers a handler on the event bus, and when any buffers are received in this handler, it writes them to itself. This enables you to write data to a NetSocket which is potentially in a completely different verticle or even in a different Vert.x instance by sending the buffer to the address of that handler.</p>
<p>The address of the handler is given by the <code>writeHandlerID()</code> method.</p>
<p>For example to write some data to the NetSocket from a completely different verticle you could do:</p>
<pre class="prettyprint">String writeHandlerID = ... // E.g. retrieve the ID from shared data

vertx.eventBus().send(writeHandlerID, buffer);
</pre>
<h3 id="read-and-write-streams">Read and Write Streams</h3><br/>
<p>NetSocket also implements <code>org.vertx.java.core.streams.ReadStream</code> and <code>org.vertx.java.core.streams.WriteStream</code>. This allows flow control to occur on the connection and the connection data to be pumped to and from other object such as HTTP requests and responses, WebSockets and asynchronous files.</p>
<p>This will be discussed in depth in the chapter on <a href="#flow-control">streams and pumps</a>.</p>
<h2 id="scaling-tcp-servers">Scaling TCP Servers</h2><br/>
<p>A verticle instance is strictly single threaded.</p>
<p>If you create a simple TCP server and deploy a single instance of it then all the handlers for that server are always executed on the same event loop (thread).</p>
<p>This means that if you are running on a server with a lot of cores, and you only have this one instance deployed then you will have at most one core utilised on your server!</p>
<p>To remedy this you can simply deploy more instances of the module in the server, e.g.</p>
<pre class="prettyprint">vertx runmod com.mycompany~my-mod~1.0 -instances 20
</pre>
<p>Or for a raw verticle</p>
<pre class="prettyprint">vertx run foo.MyApp -instances 20
</pre>
<p>The above would run 20 instances of the module/verticle in the same Vert.x instance.</p>
<p>Once you do this you will find the echo server works functionally identically to before, but, <em>as if by magic</em>, all your cores on your server can be utilised and more work can be handled.</p>
<p>At this point you might be asking yourself <em>'Hold on, how can you have more than one server listening on the same host and port? Surely you will get port conflicts as soon as you try and deploy more than one instance?'</em></p>
<p><em>Vert.x does a little magic here</em>.</p>
<p>When you deploy another server on the same host and port as an existing server it doesn't actually try and create a new server listening on the same host/port.</p>
<p>Instead it internally maintains just a single server, and, as incoming connections arrive it distributes them in a round-robin fashion to any of the connect handlers set by the verticles.</p>
<p>Consequently Vert.x TCP servers can scale over available cores while each Vert.x verticle instance remains strictly single threaded, and you don't have to do any special tricks like writing load-balancers in order to scale your server on your multi-core machine.</p>
<h2 id="netclient">NetClient</h2><br/>
<p>A NetClient is used to make TCP connections to servers.</p>
<h3 id="creating-a-net-client">Creating a Net Client</h3><br/>
<p>To create a TCP client you call the <code>createNetClient</code> method on your <code>vertx</code> instance.</p>
<pre class="prettyprint">NetClient client = vertx.createNetClient();
</pre>
<h3 id="making-a-connection">Making a Connection</h3><br/>
<p>To actually connect to a server you invoke the <code>connect</code> method:</p>
<pre class="prettyprint">NetClient client = vertx.createNetClient();

client.connect(1234, "localhost", new AsyncResultHandler&lt;NetSocket&gt;() {
    public void handle(AsyncResult&lt;NetSocket&gt; asyncResult) {
        if (asyncResult.succeeded()) {
          log.info("We have connected! Socket is " + asyncResult.result());
    } else {
          asyncResult.cause().printStackTrace();
        }
    }
});
</pre>
<p>The connect method takes the port number as the first parameter, followed by the hostname or ip address of the server. The third parameter is a connect handler. This handler will be called when the connection actually occurs.</p>
<p>The argument passed into the connect handler is an <code>AsyncResult&lt;NetSocket&gt;</code>, and the <code>NetSocket</code> can be retrieved from the <code>result()</code> method. You can read and write data from the socket in exactly the same way as you do on the server side.</p>
<p>You can also close it, set the closed handler, set the exception handler and use it as a <code>ReadStream</code> or <code>WriteStream</code> exactly the same as the server side <code>NetSocket</code>.</p>
<h3 id="configuring-reconnection">Configuring Reconnection</h3><br/>
<p>A NetClient can be configured to automatically retry connecting or reconnecting to the server in the event that it cannot connect or has lost its connection. This is done by invoking the methods <code>setReconnectAttempts</code> and <code>setReconnectInterval</code>:</p>
<pre class="prettyprint">NetClient client = vertx.createNetClient();

client.setReconnectAttempts(1000);

client.setReconnectInterval(500);
</pre>
<p><code>ReconnectAttempts</code> determines how many times the client will try to connect to the server before giving up. A value of <code>-1</code> represents an infinite number of times. The default value is <code>0</code>. I.e. no reconnection is attempted.</p>
<p><code>ReconnectInterval</code> detemines how long, in milliseconds, the client will wait between reconnect attempts. The default value is <code>1000</code>.</p>
<h3 id="netclient-properties">NetClient Properties</h3><br/>
<p>Just like <code>NetServer</code>, <code>NetClient</code> also has a set of TCP properties you can set which affect its behaviour. They have the same meaning as those on <code>NetServer</code>.</p>
<p><code>NetClient</code> also has a further set of properties which are used to configure SSL. We'll discuss those later on.</p>
<h2 id="ssl-servers">SSL Servers</h2><br/>
<p>Net servers can also be configured to work with <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">Transport Layer Security</a> (previously known as SSL).</p>
<p>When a <code>NetServer</code> is working as an SSL Server the API of the <code>NetServer</code> and <code>NetSocket</code> is identical compared to when it working with standard sockets. Getting the server to use SSL is just a matter of configuring the <code>NetServer</code> before <code>listen</code> is called.</p>
<p>To enabled SSL the function <code>setSSL(true)</code> must be called on the Net Server.</p>
<p>The server must also be configured with a <em>key store</em> and an optional <em>trust store</em>.</p>
<p>These are both <em>Java keystores</em> which can be managed using the <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html">keytool</a> utility which ships with the JDK.</p>
<p>The keytool command allows you to create keystores, and import and export certificates from them.</p>
<p>The key store should contain the server certificate. This is mandatory - the client will not be able to connect to the server over SSL if the server does not have a certificate.</p>
<p>The key store is configured on the server using the <code>setKeyStorePath()</code> and <code>setKeyStorePassword()</code> methods.</p>
<p>The trust store is optional and contains the certificates of any clients it should trust. This is only used if client authentication is required.</p>
<p>To configure a server to use server certificates only:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer()
               .setSSL(true)
               .setKeyStorePath("/path/to/your/keystore/server-keystore.jks")
               .setKeyStorePassword("password");
</pre>
<p>Making sure that <code>server-keystore.jks</code> contains the server certificate.</p>
<p>To configure a server to also require client certificates:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer()
               .setSSL(true)
               .setKeyStorePath("/path/to/your/keystore/server-keystore.jks")
               .setKeyStorePassword("password")
               .setTrustStorePath("/path/to/your/truststore/server-truststore.jks")
               .setTrustStorePassword("password")
               .setClientAuthRequired(true);
</pre>
<p>Making sure that <code>server-truststore.jks</code> contains the certificates of any clients who the server trusts.</p>
<p>If <code>clientAuthRequired</code> is set to <code>true</code> and the client cannot provide a certificate, or it provides a certificate that the server does not trust then the connection attempt will not succeed.</p>
<h2 id="ssl-clients">SSL Clients</h2><br/>
<p>Net Clients can also be easily configured to use SSL. They have the exact same API when using SSL as when using standard sockets.</p>
<p>To enable SSL on a <code>NetClient</code> the function <code>setSSL(true)</code> is called.</p>
<p>If the <code>setTrustAll(true)</code> is invoked on the client, then the client will trust all server certificates. The connection will still be encrypted but this mode is vulnerable to 'man in the middle' attacks. I.e. you can't be sure who you are connecting to. Use this with caution. Default value is <code>false</code>.</p>
<p>If <code>setTrustAll(true)</code> has not been invoked then a client trust store must be configured and should contain the certificates of the servers that the client trusts.</p>
<p>The client trust store is just a standard Java key store, the same as the key stores on the server side. The client trust store location is set by using the function <code>setTrustStorePath()</code> on the <code>NetClient</code>. If a server presents a certificate during connection which is not in the client trust store, the connection attempt will not succeed.</p>
<p>If the server requires client authentication then the client must present its own certificate to the server when connecting. This certificate should reside in the client key store. Again it's just a regular Java key store. The client keystore location is set by using the function <code>setKeyStorePath()</code> on the <code>NetClient</code>.</p>
<p>To configure a client to trust all server certificates (dangerous):</p>
<pre class="prettyprint">NetClient client = vertx.createNetClient()
               .setSSL(true)
               .setTrustAll(true);
</pre>
<p>To configure a client to only trust those certificates it has in its trust store:</p>
<pre class="prettyprint">NetClient client = vertx.createNetClient()
               .setSSL(true)
               .setTrustStorePath("/path/to/your/client/truststore/client-truststore.jks")
               .setTrustStorePassword("password");
</pre>
<p>To configure a client to only trust those certificates it has in its trust store, and also to supply a client certificate:</p>
<pre class="prettyprint">NetClient client = vertx.createNetClient()
               .setSSL(true)
               .setTrustStorePath("/path/to/your/client/truststore/client-truststore.jks")
               .setTrustStorePassword("password")
               .setClientAuthRequired(true)
               .setKeyStorePath("/path/to/keystore/holding/client/cert/client-keystore.jks")
               .setKeyStorePassword("password");
</pre>
<h1 id="user-datagram-protocol-udp">User Datagram Protocol (UDP)</h1><br/>
<p>Using User Datagram Protocol (UDP) with Vert.x is a piece of cake.</p>
<p>UDP is a connection-less transport which basically means you have no persistent connection to a remote peer.</p>
<p>Instead you can send and receive packages and the remote address is contained in each of them.</p>
<p>Beside this UDP is not as safe as TCP to use, which means there are no guarantees that a send Datagram
 packet will receive it's endpoint at all.</p>
<p>The only guarantee is that it will either receive complete or not at all.</p>
<p>Also you usually can't send data which is bigger then the MTU size of your network interface, this is because each
 packet will be send as one packet.</p>
<p>But be aware even if the packet size is smaller then the MTU it may still fail.</p>
<p>At which size it will fail depends on the Operating System etc. So rule of thumb is to try to send small packets.</p>
<p>Because of the nature of UDP it is best fit for Applications where you are allowed to drop packets (like for
 example a monitoring application).</p>
<p>The benefits are that it has a lot less overhead compared to TCP, which can be handled by the NetServer and
 NetClient (see above).</p>
<h2 id="creating-a-datagramsocket">Creating a DatagramSocket</h2><br/>
<p>To use UDP you first need t create a <code>DatagramSocket</code>. It does not matter here if you only want to send data
or send and receive.</p>
<pre class="prettyprint">DatagramSocket socket = vertx.createDatagramSocket(InternetProtocolFamily.IPV4);
</pre>
<p>The returned <code>DatagramSocket</code> will not be bound to a specific port.</p>
<p>This is not a problem if you only want to send data (like a client), but more on this in the next section.</p>
<h2 id="sending-datagram-packets">Sending Datagram packets</h2><br/>
<p>As mentioned before, User Datagram Protocol (UDP) sends data in packets to remote peers but is not connected to them in a
 persistent fashion.</p>
<p>This means each packet can be sent to a different remote peer.</p>
<p>Sending packets is as easy as shown here:</p>
<pre class="prettyprint">DatagramSocket socket = vertx.createDatagramSocket(InternetProtocolFamily.IPV4);
Buffer buffer = new Buffer("content");
// Send a Buffer
socket.send(buffer, "10.0.0.1", 1234, new AsyncResultHandler&lt;DatagramSocket&gt;() {
    public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
        log.info("Send succeeded? " + asyncResult.succeeded());
    }
});
// Send a String
socket.send("A string used as content", "10.0.0.1", 1234, new AsyncResultHandler&lt;DatagramSocket&gt;() {
    public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
        log.info("Send succeeded? " + asyncResult.succeeded());
    }
});
</pre>
<h2 id="receiving-datagram-packets">Receiving Datagram packets</h2><br/>
<p>If you want to receive packets you need to bind the <code>DatagramSocket</code> by calling <code>listen(...)</code> on it.</p>
<p>This way you will be able to receive <code>DatagramPacket</code>s that were sent to the address and port on which
the <code>DatagramSocket</code> listens.</p>
<p>Beside this you also want to set a <code>Handler</code> which will be called for each received <code>DatagramPacket</code>.</p>
<p>The <code>DatagramPacket</code> has the following methods:</p>
<ul>
<li><code>sender()</code>:   The InetSocketAddress which represent the sender of the packet</li>
<li><code>data()</code>:     The Buffer which holds the data which was received.</li>
</ul>
<p>So to listen on a specific address and port you would do something like shown here:</p>
<pre class="prettyprint">final DatagramSocket socket = vertx.createDatagramSocket(InternetProtocolFamily.IPV4);
socket.listen("0.0.0.0", 1234, new AsyncResultHandler&lt;DatagramSocket&gt;() {
    public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
        if (asyncResult.succeeded()) {
           socket.dataHandler(new Handler&lt;DatagramPacket&gt;() {
                public void handle(DatagramPacket packet) {
                    // Do something with the packet
                }
            });
        } else {
            log.warn("Listen failed", asyncResult.cause());
        }
    }
});
</pre>
<p>Be aware that even if the <code>AsyncResult</code> is successed it only means it might be written on the network stack,
but gives no guarantee that it ever reached or will reach the remote peer at all.</p>
<p>If you need such a guarantee then you want to use TCP with some handshaking logic build on top.</p>
<h2 id="multicast">Multicast</h2><br/>
<h3 id="sending-multicast-packets">Sending Multicast packets</h3><br/>
<p>Multicast allows multiple sockets to receive the same packets. This works by have same join a multicast
group to which you can send packets.</p>
<p>We will look at how you can joint a Multicast Group and so receive packets in the next section.</p>
<p>For now let us focus on how to send those. Sending multicast packets is not different to send normal
Datagram Packets.</p>
<p>The only difference is that you would pass in a multicast group address to the send method.</p>
<p>This is show here:</p>
<pre class="prettyprint">DatagramSocket socket = vertx.createDatagramSocket(InternetProtocolFamily.IPV4);
Buffer buffer = new Buffer("content");
// Send a Buffer to a multicast address
socket.send(buffer, "230.0.0.1", 1234, new AsyncResultHandler&lt;DatagramSocket&gt;() {
    public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
        log.info("Send succeeded? " + asyncResult.succeeded());
    }
});
</pre>
<p>All sockets that have joined the multicast group 230.0.0.1 will receive the packet.</p>
<h3 id="receiving-multicast-packets">Receiving Multicast packets</h3><br/>
<p>If you want to receive packets for specific Multicast group you need to bind the <code>DatagramSocket</code>
 by calling</p>
<p><code>listen(...)</code> on it and join the Multicast group.</p>
<p>This way you will be able to receive <code>DatagramPackets</code> that were sent to the address and port
 on which the <code>DatagramSocket</code> listens and also to those sent to the Multicast group.</p>
<p>Beside this you also want to set a Handler which will be called for each received DatagramPacket.</p>
<p>The <code>DatagramPacket</code> has the following methods:</p>
<ul>
<li><code>sender()</code>:   The InetSocketAddress which represent the sender of the packet</li>
<li><code>data()</code>:     The Buffer which holds the data which was received.</li>
</ul>
<p>So to listen on a specific address and port and also receive packets for the Multicast
 group 230.0.0.1 you would do something like shown here:</p>
<pre class="prettyprint">final DatagramSocket socket = vertx.createDatagramSocket(InternetProtocolFamily.IPV4);
socket.listen("0.0.0.0", 1234, new AsyncResultHandler&lt;DatagramSocket&gt;() {
    public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
        if (asyncResult.succeeded()) {
            socket.dataHandler(new Handler&lt;DatagramPacket&gt;() {
                public void handle(DatagramPacket packet) {
                    // Do something with the packet
                }
            });

            // join the multicast group
            socket.listenMulticastGroup("230.0.0.1", new AsyncResultHandler&lt;DatagramSocket&gt;() {
                public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
                    log.info("Listen succeeded? " + asyncResult.succeeded());
                }
            });
        } else {
            log.warn("Listen failed", asyncResult.cause());
        }
    }
});
</pre>
<h3 id="unlisten-leave-a-multicast-group">Unlisten / leave a Multicast group</h3><br/>
<p>There are sometimes situations where you want to receive packets for a Multicast group for
 a limited time.</p>
<p>In this situations you can first start to listen for them and then later unlisten.</p>
<p>This is shown here:</p>
<pre class="prettyprint">final DatagramSocket socket = vertx.createDatagramSocket(InternetProtocolFamily.IPV4);
socket.listen("0.0.0.0", 1234, new AsyncResultHandler&lt;DatagramSocket&gt;() {
    public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
        if (asyncResult.succeeded()) {
            socket.dataHandler(new Handler&lt;DatagramPacket&gt;() {
                public void handle(DatagramPacket packet) {
                    // Do something with the packet
                }
            });

            // join the multicast group
            socket.listenMulticastGroup("230.0.0.1", new AsyncResultHandler&lt;DatagramSocket&gt;() {
                public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
                    if (asyncResult.successed()) {

                        // will now receive packets for group
                        ...
                        ...
                        // do some work
                        ..
                        ..
                        socket.unlisten("230.0.0.1", new AsyncResultHandler&lt;DatagramSocket&gt;() {
                            public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
                                log.info("Unlisten succeeded? " + asyncResult.succeeded());
                            }
                        });

                    } else {
                       log.warn("Listen failed", asyncResult.cause());
                    }

                }
            });
        } else {
            log.warn("Listen failed", asyncResult.cause());
        }
    }
});
</pre>
<h3 id="blocking-multicast">Blocking multicast</h3><br/>
<p>Beside unlisten a Multicast address it's also possible to just block multicast for a specific sender address.</p>
<p>Be aware this only work on some Operating Systems and kernel versions. So please check the Operating System
 documentation if it's supported.</p>
<p>This an expert feature.</p>
<p>To block multicast from a specic address you can call <code>blockMulticastGroup(...)</code> on the DatagramSocket
 like shown here:</p>
<pre class="prettyprint">final DatagramSocket socket = vertx.createDatagramSocket(InternetProtocolFamily.IPV4);
...
...
// This would block packets which are send from 10.0.0.2
socket.blockMulticastGroup("230.0.0.1", "10.0.0.2", new AsyncResultHandler&lt;DatagramSocket&gt;() {
    public void handle(AsyncResult&lt;DatagramSocket&gt; asyncResult) {
        log.info("block succeeded? " + asyncResult.succeeded());
    }
});
</pre>
<h2 id="datagramsocket-properties">DatagramSocket properties</h2><br/>
<p>When using the <code>DatagramSocket</code> there are multiple properties you can set to change it's behaviour.
Those are listed here:</p>
<ul>
<li>
<p><code>setSendBufferSize(size)</code> Sets the send buffer size in bytes.</p>
</li>
<li>
<p><code>setReceiveBufferSize(size)</code> Sets the TCP receive buffer size in bytes.</p>
</li>
<li>
<p><code>setReuseAddress(reuse)</code> if <code>reuse</code> is true then addresses in TIME_WAIT state can be reused after
                         they have been closed.</p>
</li>
<li>
<p><code>setTrafficClass(trafficClass)</code></p>
</li>
<li>
<p><code>setBroadcast(broadcast)</code> Sets or clears the SO_BROADCAST socket option. When this option is set,
                            Datagram (UDP) packets may be sent to a local interface's broadcast address.</p>
</li>
<li>
<p><code>setMulticastLoopbackMode(loopbackModeDisabled)</code> Sets or clears the IP_MULTICAST_LOOP socket option.
                                                   When this option is set, multicast packets will
                                                   also be received on the local interface.</p>
</li>
<li>
<p><code>setMulticastTimeToLive(int ttl)</code> Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live,"
                                    but in this context it specifies the number of IP hops that a packet is
                                    allowed to go through, specifically for multicast traffic. Each router
                                    or gateway that forwards a packet decrements the TTL. If the TTL is
                                    decremented to 0 by a router, it will not be forwarded.</p>
</li>
</ul>
<h2 id="datagramsocket-local-address">DatagramSocket Local Address</h2><br/>
<p>You can find out the local address of the socket (i.e. the address of this side of the UDP Socket) by calling
 <code>localAddress()</code>.
This will only return an InetSocketAddress<code>if you bound the</code>DatagramSocket<code>with</code>listen(...)` before, otherwise
 it will return null.</p>
<h2 id="closing-a-datagramsocket">Closing a DatagramSocket</h2><br/>
<p>You can close a socket by invoking the <code>close</code> method. This will close the socket and release all resources</p>
<p><a id="flow-control"> </a></p>
<h1 id="flow-control-streams-and-pumps">Flow Control - Streams and Pumps</h1><br/>
<p>There are several objects in Vert.x that allow data to be read from and written to in the form of Buffers.</p>
<p>In Vert.x, calls to write data return immediately and writes are internally queued.</p>
<p>It's not hard to see that if you write to an object faster than it can actually write the data to its underlying resource then the write queue could grow without bound - eventually resulting in exhausting available memory.</p>
<p>To solve this problem a simple flow control capability is provided by some objects in the Vert.x API.</p>
<p>Any flow control aware object that can be written-to implements <code>org.vertx.java.core.streams.ReadStream</code>, and any flow control object that can be read-from is said to implement <code>org.vertx.java.core.streams.WriteStream</code>.</p>
<p>Let's take an example where we want to read from a <code>ReadStream</code> and write the data to a <code>WriteStream</code>.</p>
<p>A very simple example would be reading from a <code>NetSocket</code> on a server and writing back to the same <code>NetSocket</code> - since <code>NetSocket</code> implements both <code>ReadStream</code> and <code>WriteStream</code>, but you can do this between any <code>ReadStream</code> and any <code>WriteStream</code>, including HTTP requests and response, async files, WebSockets, etc.</p>
<p>A naive way to do this would be to directly take the data that's been read and immediately write it to the NetSocket, for example:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(final NetSocket sock) {

        sock.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer buffer) {
                // Write the data straight back
                sock.write(buffer);
            }
        });

    }
}).listen(1234, "localhost");
</pre>
<p>There's a problem with the above example: If data is read from the socket faster than it can be written back to the socket, it will build up in the write queue of the <code>NetSocket</code>, eventually running out of RAM. This might happen, for example if the client at the other end of the socket wasn't reading very fast, effectively putting back-pressure on the connection.</p>
<p>Since <code>NetSocket</code> implements <code>WriteStream</code>, we can check if the <code>WriteStream</code> is full before writing to it:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(final NetSocket sock) {

        sock.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer buffer) {
                if (!sock.writeQueueFull()) {
                    sock.write(buffer);
                }
            }
        });

    }
}).listen(1234, "localhost");
</pre>
<p>This example won't run out of RAM but we'll end up losing data if the write queue gets full. What we really want to do is pause the <code>NetSocket</code> when the write queue is full. Let's do that:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(final NetSocket sock) {

        sock.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer buffer) {
                sock.write(buffer);
                if (sock.writeQueueFull()) {
                    sock.pause();
                }
            }
        });

    }
}).listen(1234, "localhost");
</pre>
<p>We're almost there, but not quite. The <code>NetSocket</code> now gets paused when the file is full, but we also need to <em>unpause</em> it when the write queue has processed its backlog:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(final NetSocket sock) {

        sock.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer buffer) {
                sock.write(buffer);
                if (sock.writeQueueFull()) {
                    sock.pause();
                    sock.drainHandler(new VoidHandler() {
                        public void handle() {
                            sock.resume();
                        }
                    });
                }
            }
        });

    }
}).listen(1234, "localhost");
</pre>
<p>And there we have it. The <code>drainHandler</code> event handler will get called when the write queue is ready to accept more data, this resumes the <code>NetSocket</code> which allows it to read more data.</p>
<p>It's very common to want to do this when writing Vert.x applications, so we provide a helper class called <code>Pump</code> which does all this hard work for you. You just feed it the <code>ReadStream</code> and the <code>WriteStream</code> and it tell it to start:</p>
<pre class="prettyprint">NetServer server = vertx.createNetServer();

server.connectHandler(new Handler&lt;NetSocket&gt;() {
    public void handle(NetSocket sock) {
        Pump.create(sock, sock).start();
    }
}).listen(1234, "localhost");
</pre>
<p>Which does exactly the same thing as the more verbose example.</p>
<p>Let's look at the methods on <code>ReadStream</code> and <code>WriteStream</code> in more detail:</p>
<h2 id="readstream">ReadStream</h2><br/>
<p><code>ReadStream</code> is implemented by <code>HttpClientResponse</code>, <code>HttpServerRequest</code>, <code>WebSocket</code>, <code>NetSocket</code>, <code>SockJSSocket</code> and <code>AsyncFile</code>.</p>
<p>Functions:</p>
<ul>
<li><code>dataHandler(handler)</code>: set a handler which will receive data from the <code>ReadStream</code>. As data arrives the handler will be passed a Buffer.</li>
<li><code>pause()</code>: pause the handler. When paused no data will be received in the <code>dataHandler</code>.</li>
<li><code>resume()</code>: resume the handler. The handler will be called if any data arrives.</li>
<li><code>exceptionHandler(handler)</code>: Will be called if an exception occurs on the <code>ReadStream</code>.</li>
<li><code>endHandler(handler)</code>: Will be called when end of stream is reached. This might be when EOF is reached if the <code>ReadStream</code> represents a file, or when end of request is reached if it's an HTTP request, or when the connection is closed if it's a TCP socket.</li>
</ul>
<h2 id="writestream">WriteStream</h2><br/>
<p><code>WriteStream</code> is implemented by , <code>HttpClientRequest</code>, <code>HttpServerResponse</code>, <code>WebSocket</code>, <code>NetSocket</code>, <code>SockJSSocket</code> and <code>AsyncFile</code>.</p>
<p>Functions:</p>
<ul>
<li><code>write(buffer)</code>: write a Buffer to the <code>WriteStream</code>. This method will never block. Writes are queued internally and asynchronously written to the underlying resource.</li>
<li><code>setWriteQueueMaxSize(size)</code>: set the number of bytes at which the write queue is considered <em>full</em>, and the method <code>writeQueueFull()</code> returns <code>true</code>. Note that, even if the write queue is considered full, if <code>write</code> is called the data will still be accepted and queued.</li>
<li><code>writeQueueFull()</code>: returns <code>true</code> if the write queue is considered full.</li>
<li><code>exceptionHandler(handler)</code>: Will be called if an exception occurs on the <code>WriteStream</code>.</li>
<li><code>drainHandler(handler)</code>: The handler will be called if the <code>WriteStream</code> is considered no longer full.</li>
</ul>
<h2 id="pump">Pump</h2><br/>
<p>Instances of <code>Pump</code> have the following methods:</p>
<ul>
<li><code>start()</code>: Start the pump.</li>
<li><code>stop()</code>: Stops the pump. When the pump starts it is in stopped mode.</li>
<li><code>setWriteQueueMaxSize()</code>: This has the same meaning as <code>setWriteQueueMaxSize</code> on the <code>WriteStream</code>.</li>
<li><code>bytesPumped()</code>: Returns total number of bytes pumped.</li>
</ul>
<p>A pump can be started and stopped multiple times.</p>
<p>When a pump is first created it is <em>not</em> started. You need to call the <code>start()</code> method to start it.</p>
<h1 id="writing-http-servers-and-clients">Writing HTTP Servers and Clients</h1><br/>
<h2 id="writing-http-servers">Writing HTTP servers</h2><br/>
<p>Vert.x allows you to easily write full featured, highly performant and scalable HTTP servers.</p>
<h3 id="creating-an-http-server">Creating an HTTP Server</h3><br/>
<p>To create an HTTP server you call the <code>createHttpServer</code> method on your <code>vertx</code> instance.</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();
</pre>
<h3 id="start-the-server-listening_1">Start the Server Listening</h3><br/>
<p>To tell that server to listen for incoming requests you use the <code>listen</code> method:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.listen(8080, "myhost");
</pre>
<p>The first parameter to <code>listen</code> is the port.</p>
<p>The second parameter is the hostname or ip address. If it is omitted it will default to <code>0.0.0.0</code> which means it will listen at all available interfaces.</p>
<p>The actual bind is asynchronous so the server might not actually be listening until some time <em>after</em> the call to listen has returned. If you want to be notified when the server is actually listening you can provide a handler to the <code>listen</code> call. For example:</p>
<pre class="prettyprint">server.listen(8080, "myhost", new AsyncResultHandler&lt;Void&gt;() {
    public void handle(AsyncResult&lt;HttpServer&gt; asyncResult) {
        log.info("Listen succeeded? " + asyncResult.succeeded());
    }
});
</pre>
<h3 id="getting-notified-of-incoming-requests">Getting Notified of Incoming Requests</h3><br/>
<p>To be notified when a request arrives you need to set a request handler. This is done by calling the <code>requestHandler</code> method of the server, passing in the handler:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest request) {
        log.info("A request has arrived on the server!");
        request.response().end();
    }
});

server.listen(8080, "localhost");
</pre>
<p>Every time a request arrives on the server the handler is called passing in an instance of <code>org.vertx.java.core.http.HttpServerRequest</code>.</p>
<p>You can try it by running the verticle and pointing your browser at <code>http://localhost:8080</code>.</p>
<p>Similarly to <code>NetServer</code>, the return value of the <code>requestHandler</code> method is the server itself, so multiple invocations can be chained together. That means we can rewrite the above with:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest request) {
        log.info("A request has arrived on the server!");
        request.response().end();
    }
}).listen(8080, "localhost");
</pre>
<p>Or:</p>
<pre class="prettyprint">vertx.createHttpServer().requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest request) {
        log.info("A request has arrived on the server!");
        request.response().end();
    }
}).listen(8080, "localhost");
</pre>
<h3 id="handling-http-requests">Handling HTTP Requests</h3><br/>
<p>So far we have seen how to create an <code>HttpServer</code> and be notified of requests. Lets take a look at how to handle the requests and do something useful with them.</p>
<p>When a request arrives, the request handler is called passing in an instance of <code>HttpServerRequest</code>. This object represents the server side HTTP request.</p>
<p>The handler is called when the headers of the request have been fully read. If the request contains a body, that body may arrive at the server some time after the request handler has been called.</p>
<p>It contains functions to get the URI, path, request headers and request parameters. It also contains a <code>response()</code> method which returns a reference to an object that represents the server side HTTP response for the object.</p>
<h4 id="request-method">Request Method</h4><br/>
<p>The request object has a method <code>method()</code> which returns a string representing what HTTP method was requested. Possible return values for <code>method()</code> are: <code>GET</code>, <code>PUT</code>, <code>POST</code>, <code>DELETE</code>, <code>HEAD</code>, <code>OPTIONS</code>, <code>CONNECT</code>, <code>TRACE</code>, <code>PATCH</code>.</p>
<h4 id="request-version">Request Version</h4><br/>
<p>The request object has a method <code>version()</code> which returns an enum representing the HTTP version.</p>
<h4 id="request-uri">Request URI</h4><br/>
<p>The request object has a method <code>uri()</code> which returns the full URI (Uniform Resource Locator) of the request. For example, if the request URI was:</p>
<pre class="prettyprint">/a/b/c/page.html?param1=abc&amp;param2=xyz
</pre>
<p>Then <code>request.uri()</code> would return the string <code>/a/b/c/page.html?param1=abc&amp;param2=xyz</code>.</p>
<p>Request URIs can be relative or absolute (with a domain) depending on what the client sent. In most cases they will be relative.</p>
<p>The request uri contains the value as defined in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html">Section 5.1.2 of the HTTP specification - Request-URI</a></p>
<h4 id="request-path">Request Path</h4><br/>
<p>The request object has a method <code>path()</code> which returns the path of the request. For example, if the request URI was:</p>
<pre class="prettyprint">a/b/c/page.html?param1=abc&amp;param2=xyz
</pre>
<p>Then <code>request.path()</code> would return the string <code>/a/b/c/page.html</code></p>
<h4 id="request-query">Request Query</h4><br/>
<p>The request object has a method <code>query()</code> which contains the query of the request. For example, if the request URI was:</p>
<pre class="prettyprint">a/b/c/page.html?param1=abc&amp;param2=xyz
</pre>
<p>Then <code>request.query()</code> would return the string <code>param1=abc&amp;param2=xyz</code></p>
<h4 id="request-headers">Request Headers</h4><br/>
<p>The request headers are available using the <code>headers()</code> method on the request object.</p>
<p>The returned object is an instance of <code>org.vertx.java.core.MultiMap</code>. A MultiMap allows multiple values for the same key, unlike a normal Map.</p>
<p>Here's an example that echoes the headers to the output of the response. Run it and point your browser at <code>http://localhost:8080</code> to see the headers.</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest request) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry&lt;String, String&gt; header: request.headers().entries()) {
            sb.append(header.getKey()).append(": ").append(header.getValue()).append("\n");
        }
        request.response().putHeader("content-type", "text/plain");
        request.response().end(sb.toString());
    }
}).listen(8080, "localhost");
</pre>
<h4 id="request-params">Request params</h4><br/>
<p>Similarly to the headers, the request parameters are available using the <code>params()</code> method on the request object.</p>
<p>The returned object is an instance of <code>org.vertx.java.core.MultiMap</code>.</p>
<p>Request parameters are sent on the request URI, after the path. For example if the URI was:</p>
<pre class="prettyprint">/page.html?param1=abc&amp;param2=xyz
</pre>
<p>Then the params multimap would contain the following entries:</p>
<pre class="prettyprint">param1: 'abc'
param2: 'xyz
</pre>
<h4 id="remote-address">Remote Address</h4><br/>
<p>Use the method <code>remoteAddress()</code> to find out the address of the other side of the HTTP connection.</p>
<h4 id="absolute-uri">Absolute URI</h4><br/>
<p>Use the method <code>absoluteURI()</code> to return the absolute URI corresponding to the request.</p>
<h4 id="reading-data-from-the-request-body">Reading Data from the Request Body</h4><br/>
<p>Sometimes an HTTP request contains a request body that we want to read. As previously mentioned the request handler is called when only the headers of the request have arrived so the <code>HttpServerRequest</code> object does not contain the body. This is because the body may be very large and we don't want to create problems with exceeding available memory.</p>
<p>To receive the body, you set the <code>dataHandler</code> on the request object. This will then get called every time a chunk of the request body arrives. Here's an example:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest request) {
        request.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer buffer) {
                log.info('I received ' + buffer.length() + ' bytes');
            }
        });

    }
}).listen(8080, "localhost");
</pre>
<p>The <code>dataHandler</code> may be called more than once depending on the size of the body.</p>
<p>You'll notice this is very similar to how data from <code>NetSocket</code> is read.</p>
<p>The request object implements the <code>ReadStream</code> interface so you can pump the request body to a <code>WriteStream</code>. See the chapter on <a href="#flow-control">streams and pumps</a> for a detailed explanation.</p>
<p>In many cases, you know the body is not large and you just want to receive it in one go. To do this you could do something like the following:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest request) {

        final Buffer body = new Buffer(0);

        request.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer buffer) {
                body.appendBuffer(buffer);
            }
        });
        request.endHandler(new VoidHandler() {
            public void handle() {
              // The entire body has now been received
              log.info("The total body received was " + body.length() + " bytes");
            }
        });

    }
}).listen(8080, "localhost");
</pre>
<p>Like any <code>ReadStream</code> the end handler is invoked when the end of stream is reached - in this case at the end of the request.</p>
<p>If the HTTP request is using HTTP chunking, then each HTTP chunk of the request body will correspond to a single call of the data handler.</p>
<p>It's a very common use case to want to read the entire body before processing it, so Vert.x allows a <code>bodyHandler</code> to be set on the request object.</p>
<p>The body handler is called only once when the <em>entire</em> request body has been read.</p>
<p><em>Beware of doing this with very large requests since the entire request body will be stored in memory.</em></p>
<p>Here's an example using <code>bodyHandler</code>:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest request) {
        request.bodyHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer body) {
              // The entire body has now been received
              log.info("The total body received was " + body.length() + " bytes");
            }
        });
    }
}).listen(8080, "localhost");
</pre>
<h4 id="handling-multipart-form-uploads">Handling Multipart Form Uploads</h4><br/>
<p>Vert.x understands file uploads submitted from HTML forms in browsers. In order to handle file uploads you should set the <code>uploadHandler</code> on the request. The handler will be called once for each upload in the form.</p>
<pre class="prettyprint">request.expectMultiPart(true);

request.uploadHandler(new Handler&lt;HttpServerFileUpload&gt;() {
    public void handle(HttpServerFileUpload upload) {
    }
});
</pre>
<p>The <code>HttpServerFileUpload</code> class implements <code>ReadStream</code> so you read the data and stream it to any object that implements <code>WriteStream</code> using a Pump, as previously discussed.</p>
<p>You can also stream it directly to disk using the convenience method <code>streamToFileSystem()</code>.</p>
<pre class="prettyprint">request.expectMultiPart(true);

request.uploadHandler(new Handler&lt;HttpServerFileUpload&gt;() {
    public void handle(HttpServerFileUpload upload) {
        upload.streamToFileSystem("uploads/" + upload.filename());
    }
});
</pre>
<h4 id="handling-multipart-form-attributes">Handling Multipart Form Attributes</h4><br/>
<p>If the request corresponds to an HTML form that was submitted you can use the method <code>formAttributes</code> to retrieve a Multi Map of the form attributes. This should only be called after <em>all</em> of the request has been read - this is because form attributes are encoded in the request <em>body</em> not in the request headers.</p>
<pre class="prettyprint">request.endHandler(new VoidHandler() {
    public void handle() {
        // The request has been all ready so now we can look at the form attributes
        MultiMap attrs = request.formAttributes();
        // Do something with them
    }
});
</pre>
<h3 id="http-server-responses">HTTP Server Responses</h3><br/>
<p>As previously mentioned, the HTTP request object contains a method <code>response()</code>. This returns the HTTP response for the request. You use it to write the response back to the client.</p>
<h3 id="setting-status-code-and-message">Setting Status Code and Message</h3><br/>
<p>To set the HTTP status code for the response use the <code>setStatusCode()</code> method, e.g.</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest request) {
        request.response().setStatusCode(739).setStatusMessage("Too many gerbils").end();
    }
}).listen(8080, "localhost");
</pre>
<p>You can also use the <code>setStatusMessage()</code> method to set the status message. If you do not set the status message a default message will be used.</p>
<p>The default value for <code>statusCode</code> is <code>200</code>.</p>
<h4 id="writing-http-responses">Writing HTTP responses</h4><br/>
<p>To write data to an HTTP response, you invoke the <code>write</code> function. This function can be invoked multiple times before the response is ended. It can be invoked in a few ways:</p>
<p>With a single buffer:</p>
<pre class="prettyprint">Buffer myBuffer = ...
request.response().write(myBuffer);
</pre>
<p>A string. In this case the string will encoded using UTF-8 and the result written to the wire.</p>
<pre class="prettyprint">request.response().write("hello");
</pre>
<p>A string and an encoding. In this case the string will encoded using the specified encoding and the result written to the wire.</p>
<pre class="prettyprint">request.response().write("hello", "UTF-16");
</pre>
<p>The <code>write</code> function is asynchronous and always returns immediately after the write has been queued.</p>
<p>If you are just writing a single string or Buffer to the HTTP response you can write it and end the response in a single call to the <code>end</code> method.</p>
<p>The first call to <code>write</code> results in the response header being being written to the response.</p>
<p>Consequently, if you are not using HTTP chunking then you must set the <code>Content-Length</code> header before writing to the response, since it will be too late otherwise. If you are using HTTP chunking you do not have to worry.</p>
<h4 id="ending-http-responses">Ending HTTP responses</h4><br/>
<p>Once you have finished with the HTTP response you must call the <code>end()</code> function on it.</p>
<p>This function can be invoked in several ways:</p>
<p>With no arguments, the response is simply ended.</p>
<pre class="prettyprint">request.response().end();
</pre>
<p>The function can also be called with a string or Buffer in the same way <code>write</code> is called. In this case it's just the same as calling write with a string or Buffer followed by calling <code>end</code> with no arguments. For example:</p>
<pre class="prettyprint">request.response().end("That's all folks");
</pre>
<h4 id="closing-the-underlying-connection">Closing the underlying connection</h4><br/>
<p>You can close the underlying TCP connection of the request by calling the <code>close</code> method.</p>
<pre class="prettyprint">request.response().close();
</pre>
<h4 id="response-headers">Response headers</h4><br/>
<p>HTTP response headers can be added to the response by adding them to the multimap returned from the <code>headers()</code> method:</p>
<pre class="prettyprint">request.response().headers().set("Cheese", "Stilton");
request.response().headers().set("Hat colour", "Mauve");
</pre>
<p>Individual HTTP response headers can also be written using the <code>putHeader</code> method. This allows a fluent API since calls to <code>putHeader</code> can be chained:</p>
<pre class="prettyprint">request.response().putHeader("Some-Header", "elephants").putHeader("Pants", "Absent");
</pre>
<p>Response headers must all be added before any parts of the response body are written.</p>
<h4 id="chunked-http-responses-and-trailers">Chunked HTTP Responses and Trailers</h4><br/>
<p>Vert.x supports <a href="http://en.wikipedia.org/wiki/Chunked_transfer_encoding">HTTP Chunked Transfer Encoding</a>. This allows the HTTP response body to be written in chunks, and is normally used when a large response body is being streamed to a client, whose size is not known in advance.</p>
<p>You put the HTTP response into chunked mode as follows:</p>
<pre class="prettyprint">req.response().setChunked(true);
</pre>
<p>Default is non-chunked. When in chunked mode, each call to <code>response.write(...)</code> will result in a new HTTP chunk being written out.</p>
<p>When in chunked mode you can also write HTTP response trailers to the response. These are actually written in the final chunk of the response.</p>
<p>To add trailers to the response, add them to the multimap returned from the <code>trailers()</code> method:</p>
<pre class="prettyprint">request.response().trailers().add("Philosophy", "Solipsism");
request.response().trailers().add("Favourite-Shakin-Stevens-Song", "Behind the Green Door");
</pre>
<p>Like headers, individual HTTP response trailers can also be written using the <code>putTrailer()</code> method. This allows a fluent API since calls to <code>putTrailer</code> can be chained:</p>
<pre class="prettyprint">request.response().putTrailer("Cat-Food", "Whiskas").putTrailer("Eye-Wear", "Monocle");
</pre>
<h3 id="serving-files-directly-from-disk">Serving files directly from disk</h3><br/>
<p>If you were writing a web server, one way to serve a file from disk would be to open it as an <code>AsyncFile</code> and pump it to the HTTP response. Or you could load it it one go using the file system API and write that to the HTTP response.</p>
<p>Alternatively, Vert.x provides a method which allows you to serve a file from disk to an HTTP response in one operation. Where supported by the underlying operating system this may result in the OS directly transferring bytes from the file to the socket without being copied through userspace at all.</p>
<p>Using <code>sendFile</code> is usually more efficient for large files, but may be slower for small files than using <code>readFile</code> to manually read the file as a buffer and write it directly to the response.</p>
<p>To do this use the <code>sendFile</code> function on the HTTP response. Here's a simple HTTP web server that serves static files from the local <code>web</code> directory:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest req) {
      String file = "";
      if (req.path().equals("/")) {
        file = "index.html";
      } else if (!req.path().contains("..")) {
        file = req.path();
      }
      req.response().sendFile("web/" + file);
    }
}).listen(8080, "localhost");
</pre>
<p>There's also a version of <code>sendFile</code> which takes the name of a file to serve if the specified file cannot be found:</p>
<pre class="prettyprint">req.response().sendFile("web/" + file, "handler_404.html");
</pre>
<p><em>Note: If you use <code>sendFile</code> while using HTTPS it will copy through userspace, since if the kernel is copying data directly from disk to socket it doesn't give us an opportunity to apply any encryption.</em></p>
<p><strong>If you're going to write web servers using Vert.x be careful that users cannot exploit the path to access files outside the directory from which you want to serve them.</strong></p>
<h3 id="pumping-responses">Pumping Responses</h3><br/>
<p>Since the HTTP Response implements <code>WriteStream</code> you can pump to it from any <code>ReadStream</code>, e.g. an <code>AsyncFile</code>, <code>NetSocket</code>, <code>WebSocket</code> or <code>HttpServerRequest</code>.</p>
<p>Here's an example which echoes HttpRequest headers and body back in the HttpResponse.
 It uses a pump for the body, so it will work even if the HTTP request body is much larger than can fit in memory at any one time:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.requestHandler(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(final HttpServerRequest req) {
      req.response().headers().set(req.headers());
      Pump.createPump(req, req.response()).start();
      req.endHandler(new VoidHandler() {
        public void handle() {
            req.response().end();
        }
      });
    }
}).listen(8080, "localhost");
</pre>
<h3 id="http-compression">HTTP Compression</h3><br/>
<p>Vert.x comes with support for HTTP Compression out of the box.
Which means you are able to automatically compress the body of the responses before they are sent back to the Client.
If the client does not support HTTP Compression the responses are sent back without compressing the body.
This allows to handle Client that support HTTP Compression and those that not support it at the same time.</p>
<p>To enable compression you only need to do:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();
server.setCompressionSupported(true);
</pre>
<p>The default is false.</p>
<p>When HTTP Compression is enabled the <code>HttpServer</code> will check if the client did include an 'Accept-Encoding' header which
includes the supported compressions. Common used are deflate and gzip. Both are supported by Vert.x.
Once such a header is found the <code>HttpServer</code> will automatically compress the body of the response with one of the supported
compressions and send it back to the client.</p>
<p>Be aware that compression may be able to reduce network traffic but is more cpu-intensive.</p>
<h2 id="writing-http-clients">Writing HTTP Clients</h2><br/>
<h3 id="creating-an-http-client">Creating an HTTP Client</h3><br/>
<p>To create an HTTP client you call the <code>createHttpClient</code> method on your <code>vertx</code> instance:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient();
</pre>
<p>You set the port and hostname (or ip address) that the client will connect to using the <code>setHost</code> and <code>setPort</code> functions:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient();
client.setPort(8181);
client.setHost("foo.com");
</pre>
<p>This, of course, can be chained:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient()
    .setPort(8181)
    .setHost("foo.com");
</pre>
<p>A single <code>HTTPClient</code> always connects to the same host and port. If you want to connect to different servers, create more instances.</p>
<p>The default port is <code>80</code> and the default host is <code>localhost</code>. So if you don't explicitly set these values that's what the client will attempt to connect to.</p>
<h3 id="pooling-and-keep-alive">Pooling and Keep Alive</h3><br/>
<p>By default the <code>HTTPClient</code> pools HTTP connections. As you make requests a connection is borrowed from the pool and returned when the HTTP response has ended.</p>
<p>If you do not want connections to be pooled you can call <code>setKeepAlive</code> with <code>false</code>:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient()
               .setPort(8181)
               .setHost("foo.com").
               .setKeepAlive(false);
</pre>
<p>In this case a new connection will be created for each HTTP request and closed once the response has ended.</p>
<p>You can set the maximum number of connections that the client will pool as follows:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient()
               .setPort(8181)
               .setHost("foo.com").
               .setMaxPoolSize(10);
</pre>
<p>The default value is <code>1</code>.</p>
<h3 id="closing-the-client">Closing the client</h3><br/>
<p>Any HTTP clients created in a verticle are automatically closed for you when the verticle is stopped, however if you want to close it explicitly you can:</p>
<pre class="prettyprint">client.close();
</pre>
<h3 id="making-requests">Making Requests</h3><br/>
<p>To make a request using the client you invoke one the methods named after the HTTP method that you want to invoke.</p>
<p>For example, to make a <code>POST</code> request:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

HttpClientRequest request = client.post("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {
        log.info("Got a response: " + resp.statusCode());
    }
});

request.end();
</pre>
<p>To make a PUT request use the <code>put</code> method, to make a GET request use the <code>get</code> method, etc.</p>
<p>Legal request methods are: <code>get</code>, <code>put</code>, <code>post</code>, <code>delete</code>, <code>head</code>, <code>options</code>, <code>connect</code>, <code>trace</code> and <code>patch</code>.</p>
<p>The general modus operandi is you invoke the appropriate method passing in the request URI as the first parameter, the second parameter is an event handler which will get called when the corresponding response arrives. The response handler is passed the client response object as an argument.</p>
<p>The value specified in the request URI corresponds to the Request-URI as specified in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html">Section 5.1.2 of the HTTP specification</a>. <em>In most cases it will be a relative URI</em>.</p>
<p><em>Please note that the domain/port that the client connects to is determined by <code>setPort</code> and <code>setHost</code>, and is not parsed from the uri.</em></p>
<p>The return value from the appropriate request method is an instance of <code>org.vertx.java.core.http.HTTPClientRequest</code>. You can use this to add headers to the request, and to write to the request body. The request object implements <code>WriteStream</code>.</p>
<p>Once you have finished with the request you must call the <code>end()</code> method.</p>
<p>If you don't know the name of the request method in advance there is a general <code>request</code> method which takes the HTTP method as a parameter:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

HttpClientRequest request = client.request("POST", "/some-path/",
    new Handler&lt;HttpClientResponse&gt;() {
        public void handle(HttpClientResponse resp) {
            log.info("Got a response: " + resp.statusCode());
        }
    });

request.end();
</pre>
<p>There is also a method called <code>getNow</code> which does the same as <code>get</code>, but automatically ends the request. This is useful for simple GETs which don't have a request body:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

client.getNow("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {
        log.info("Got a response: " + resp.statusCode());
    }
});
</pre>
<h4 id="handling-exceptions">Handling exceptions</h4><br/>
<p>You can set an exception handler on the <code>HttpClient</code> class and it will receive all exceptions for the client unless a specific exception handler has been set on a specific <code>HttpClientRequest</code> object.</p>
<h4 id="writing-to-the-request-body">Writing to the request body</h4><br/>
<p>Writing to the client request body has a very similar API to writing to the server response body.</p>
<p>To write data to an <code>HttpClientRequest</code> object, you invoke the <code>write</code> function. This function can be called multiple times before the request has ended. It can be invoked in a few ways:</p>
<p>With a single buffer:</p>
<pre class="prettyprint">Buffer myBuffer = ...
request.write(myBuffer);
</pre>
<p>A string. In this case the string will encoded using UTF-8 and the result written to the wire.</p>
<pre class="prettyprint">request.write("hello");
</pre>
<p>A string and an encoding. In this case the string will encoded using the specified encoding and the result written to the wire.</p>
<pre class="prettyprint">request.write("hello", "UTF-16");
</pre>
<p>The <code>write</code> function is asynchronous and always returns immediately after the write has been queued. The actual write might complete some time later.</p>
<p>If you are just writing a single string or Buffer to the HTTP request you can write it and end the request in a single call to the <code>end</code> function.</p>
<p>The first call to <code>write</code> will result in the request headers being written to the request. Consequently, if you are not using HTTP chunking then you must set the <code>Content-Length</code> header before writing to the request, since it will be too late otherwise. If you are using HTTP chunking you do not have to worry.</p>
<h4 id="ending-http-requests">Ending HTTP requests</h4><br/>
<p>Once you have finished with the HTTP request you must call the <code>end</code> function on it.</p>
<p>This function can be invoked in several ways:</p>
<p>With no arguments, the request is simply ended.</p>
<pre class="prettyprint">request.end();
</pre>
<p>The function can also be called with a string or Buffer in the same way <code>write</code> is called. In this case it's just the same as calling write with a string or Buffer followed by calling <code>end</code> with no arguments.</p>
<h4 id="writing-request-headers">Writing Request Headers</h4><br/>
<p>To write headers to the request, add them to the multi-map returned from the <code>headers()</code> method:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

HttpClientRequest request = client.post("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {
        log.info("Got a response: " + resp.statusCode());
    }
});

request.headers().set("Some-Header", "Some-Value");
request.end();
</pre>
<p>You can also adds them using the <code>putHeader</code> method. This enables a more fluent API since calls can be chained, for example:</p>
<pre class="prettyprint">request.putHeader("Some-Header", "Some-Value").putHeader("Some-Other", "Blah");
</pre>
<p>These can all be chained together as per the common Vert.x API pattern:</p>
<pre class="prettyprint">client.setHost("foo.com").post("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {
        log.info("Got a response: " + resp.statusCode());
    }
}).putHeader("Some-Header", "Some-Value").end();
</pre>
<h4 id="request-timeouts">Request timeouts</h4><br/>
<p>You can set a timeout for specific Http Request using the <code>setTimeout()</code> method. If the request does not return any data within the timeout period an exception will be passed to the exception handler (if provided) and the request will be closed.</p>
<h4 id="http-chunked-requests">HTTP chunked requests</h4><br/>
<p>Vert.x supports <a href="http://en.wikipedia.org/wiki/Chunked_transfer_encoding">HTTP Chunked Transfer Encoding</a> for requests. This allows the HTTP request body to be written in chunks, and is normally used when a large request body is being streamed to the server, whose size is not known in advance.</p>
<p>You put the HTTP request into chunked mode as follows:</p>
<pre class="prettyprint">request.setChunked(true);
</pre>
<p>Default is non-chunked. When in chunked mode, each call to <code>request.write(...)</code> will result in a new HTTP chunk being written out.</p>
<h3 id="http-client-responses">HTTP Client Responses</h3><br/>
<p>Client responses are received as an argument to the response handler that is passed into one of the request methods on the HTTP client.</p>
<p>The response object implements <code>ReadStream</code>, so it can be pumped to a <code>WriteStream</code> like any other <code>ReadStream</code>.</p>
<p>To query the status code of the response use the <code>statusCode()</code> method. The <code>statusMessage()</code> method contains the status message. For example:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

client.getNow("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {
        log.info('server returned status code: ' + resp.statusCode());
        log.info('server returned status message: ' + resp.statusMessage());
    }
});
</pre>
<h4 id="reading-data-from-the-response-body">Reading Data from the Response Body</h4><br/>
<p>The API for reading an HTTP client response body is very similar to the API for reading a HTTP server request body.</p>
<p>Sometimes an HTTP response contains a body that we want to read. Like an HTTP request, the client response handler is called when all the response headers have arrived, not when the entire response body has arrived.</p>
<p>To receive the response body, you set a <code>dataHandler</code> on the response object which gets called as parts of the HTTP response arrive. Here's an example:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

client.getNow("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {
        resp.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer data) {
                log.info('I received ' + buffer.length() + ' bytes');
            }
        });
    }
});
</pre>
<p>The response object implements the <code>ReadStream</code> interface so you can pump the response body to a <code>WriteStream</code>. See the chapter on <a href="#flow-control">streams and pump</a> for a detailed explanation.</p>
<p>The <code>dataHandler</code> can be called multiple times for a single HTTP response.</p>
<p>As with a server request, if you wanted to read the entire response body before doing something with it you could do something like the following:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

client.getNow("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {

        final Buffer body = new Buffer(0);

        resp.dataHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer data) {
                body.appendBuffer(data);
            }
        });
        resp.endHandler(new VoidHandler() {
            public void handle() {
               // The entire response body has been received
               log.info('The total body received was ' + body.length() + ' bytes');
            }
        });
    }
});
</pre>
<p>Like any <code>ReadStream</code> the end handler is invoked when the end of stream is reached - in this case at the end of the response.</p>
<p>If the HTTP response is using HTTP chunking, then each chunk of the response body will correspond to a single call to the <code>dataHandler</code>.</p>
<p>It's a very common use case to want to read the entire body in one go, so Vert.x allows a <code>bodyHandler</code> to be set on the response object.</p>
<p>The body handler is called only once when the <em>entire</em> response body has been read.</p>
<p><em>Beware of doing this with very large responses since the entire response body will be stored in memory.</em></p>
<p>Here's an example using <code>bodyHandler</code>:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

client.getNow("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {
        resp.bodyHandler(new Handler&lt;Buffer&gt;() {
            public void handle(Buffer body) {
               // The entire response body has been received
               log.info("The total body received was " + body.length() + " bytes");
            }
        });
    }
});
</pre>
<h4 id="reading-cookies">Reading cookies</h4><br/>
<p>You can read the list of cookies from the response using the method <code>cookies()</code>.</p>
<h3 id="100-continue-handling">100-Continue Handling</h3><br/>
<p>According to the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html">HTTP 1.1 specification</a> a client can set a header <code>Expect: 100-Continue</code> and send the request header before sending the rest of the request body.</p>
<p>The server can then respond with an interim response status <code>Status: 100 (Continue)</code> to signify the client is ok to send the rest of the body.</p>
<p>The idea here is it allows the server to authorise and accept/reject the request before large amounts of data is sent. Sending large amounts of data if the request might not be accepted is a waste of bandwidth and ties up the server in reading data that it will just discard.</p>
<p>Vert.x allows you to set a <code>continueHandler</code> on the client request object. This will be called if the server sends back a <code>Status: 100 (Continue)</code> response to signify it is ok to send the rest of the request.</p>
<p>This is used in conjunction with the <code>sendHead</code> function to send the head of the request.</p>
<p>An example will illustrate this:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

final HttpClientRequest request = client.put("/some-path/", new Handler&lt;HttpClientResponse&gt;() {
    public void handle(HttpClientResponse resp) {
        log.info("Got a response " + resp.statusCode());
    }
});

request.putHeader("Expect", "100-Continue");

request.continueHandler(new VoidHandler() {
    public void handle() {

        // OK to send rest of body
        request.write("Some data").end();
    }
});

request.sendHead();
</pre>
<h3 id="http-compression_1">HTTP Compression</h3><br/>
<p>Vert.x comes with support for HTTP Compression out of the box. Which means the HTTPClient can let the remote Http server know that it supports compression, and so will be able to handle
compressed response bodies. A Http server is free to either compress with one of the supported compression algorithm or send the body back without compress it at all. So this
is only a hint for the Http server which it may ignore at all.</p>
<p>To tell the Http server which compression is supported by the <code>HttpClient</code> it will include a 'Accept-Encoding' header with the supported
compression algorithm as value. Multiple compression algorithms are supported. In case of Vert.x this will result in have the
following header added:</p>
<pre class="prettyprint">Accept-Encoding: gzip, deflate
</pre>
<p>The Http Server will choose then from one of these. You can detect if a HttpServer did compress the body by checking for the
'Content-Encoding' header in the response sent back from it.</p>
<p>If the body of the response was compressed via gzip it will include for example the following header:</p>
<pre class="prettyprint">Content-Encoding: gzip
</pre>
<p>To enable compression you only need to do:</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient();
client.setTryUseCompression(true);
</pre>
<p>The default is false.</p>
<h2 id="pumping-requests-and-responses">Pumping Requests and Responses</h2><br/>
<p>The HTTP client and server requests and responses all implement either <code>ReadStream</code> or <code>WriteStream</code>. This means you can pump between them and any other read and write streams.</p>
<h2 id="https-servers">HTTPS Servers</h2><br/>
<p>HTTPS servers are very easy to write using Vert.x.</p>
<p>An HTTPS server has an identical API to a standard HTTP server. Getting the server to use HTTPS is just a matter of configuring the HTTP Server before <code>listen</code> is called.</p>
<p>Configuration of an HTTPS server is done in exactly the same way as configuring a <code>NetServer</code> for SSL. Please see SSL server chapter for detailed instructions.</p>
<h2 id="https-clients">HTTPS Clients</h2><br/>
<p>HTTPS clients can also be very easily written with Vert.x</p>
<p>Configuring an HTTP client for HTTPS is done in exactly the same way as configuring a <code>NetClient</code> for SSL. Please see SSL client chapter for detailed instructions.</p>
<h2 id="scaling-http-servers">Scaling HTTP servers</h2><br/>
<p>Scaling an HTTP or HTTPS server over multiple cores is as simple as deploying more instances of the verticle. For example:</p>
<pre class="prettyprint">vertx runmod com.mycompany~my-mod~1.0 -instance 20
</pre>
<p>Or, for a raw verticle:</p>
<pre class="prettyprint">vertx run foo.MyServer -instances 20
</pre>
<p>The scaling works in the same way as scaling a <code>NetServer</code>. Please see the chapter on scaling Net Servers for a detailed explanation of how this works.</p>
<h1 id="routing-http-requests-with-pattern-matching">Routing HTTP requests with Pattern Matching</h1><br/>
<p>Vert.x lets you route HTTP requests to different handlers based on pattern matching on the request path. It also enables you to extract values from the path and use them as parameters in the request.</p>
<p>This is particularly useful when developing REST-style web applications.</p>
<p>To do this you simply create an instance of <code>org.vertx.java.core.http.RouteMatcher</code> and use it as handler in an HTTP server. See the chapter on HTTP servers for more information on setting HTTP handlers. Here's an example:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

RouteMatcher routeMatcher = new RouteMatcher();

server.requestHandler(routeMatcher).listen(8080, "localhost");
</pre>
<h2 id="specifying-matches">Specifying matches.</h2><br/>
<p>You can then add different matches to the route matcher. For example, to send all GET requests with path <code>/animals/dogs</code> to one handler and all GET requests with path <code>/animals/cats</code> to another handler you would do:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

RouteMatcher routeMatcher = new RouteMatcher();

routeMatcher.get("/animals/dogs", new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest req) {
        req.response().end("You requested dogs");
    }
});
routeMatcher.get("/animals/cats", new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest req) {
        req.response().end("You requested cats");
    }
});

server.requestHandler(routeMatcher).listen(8080, "localhost");
</pre>
<p>Corresponding methods exist for each HTTP method - <code>get</code>, <code>post</code>, <code>put</code>, <code>delete</code>, <code>head</code>, <code>options</code>, <code>trace</code>, <code>connect</code> and <code>patch</code>.</p>
<p>There's also an <code>all</code> method which applies the match to any HTTP request method.</p>
<p>The handler specified to the method is just a normal HTTP server request handler, the same as you would supply to the <code>requestHandler</code> method of the HTTP server.</p>
<p>You can provide as many matches as you like and they are evaluated in the order you added them, the first matching one will receive the request.</p>
<p>A request is sent to at most one handler.</p>
<h2 id="extracting-parameters-from-the-path">Extracting parameters from the path</h2><br/>
<p>If you want to extract parameters from the path, you can do this too, by using the <code>:</code> (colon) character to denote the name of a parameter. For example:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

RouteMatcher routeMatcher = new RouteMatcher();

routeMatcher.put("/:blogname/:post", new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest req) {
        String blogName = req.params().get("blogname");
        String post = req.params().get("post");
        req.response().end("blogname is " + blogName + ", post is " + post);
    }
});

server.requestHandler(routeMatcher).listen(8080, "localhost");
</pre>
<p>Any params extracted by pattern matching are added to the map of request parameters.</p>
<p>In the above example, a PUT request to <code>/myblog/post1</code> would result in the variable <code>blogName</code> getting the value <code>myblog</code> and the variable <code>post</code> getting the value <code>post1</code>.</p>
<p>Valid parameter names must start with a letter of the alphabet and be followed by any letters of the alphabet or digits or the underscore character.</p>
<h2 id="extracting-params-using-regular-expressions">Extracting params using Regular Expressions</h2><br/>
<p>Regular Expressions can be used to extract more complex matches. In this case capture groups are used to capture any parameters.</p>
<p>Since the capture groups are not named they are added to the request with names <code>param0</code>, <code>param1</code>, <code>param2</code>, etc.</p>
<p>Corresponding methods exist for each HTTP method - <code>getWithRegEx</code>, <code>postWithRegEx</code>, <code>putWithRegEx</code>, <code>deleteWithRegEx</code>, <code>headWithRegEx</code>, <code>optionsWithRegEx</code>, <code>traceWithRegEx</code>, <code>connectWithRegEx</code> and <code>patchWithRegEx</code>.</p>
<p>There's also an <code>allWithRegEx</code> method which applies the match to any HTTP request method.</p>
<p>For example:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

RouteMatcher routeMatcher = new RouteMatcher();

routeMatcher.allWithRegEx("\\/([^\\/]+)\\/([^\\/]+)", new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest req) {
        String first = req.params().get("param0");
        String second = req.params().get("param1");
        req.response.end("first is " + first + " and second is " + second);
    }
});

server.requestHandler(routeMatcher).listen(8080, "localhost");
</pre>
<p>Run the above and point your browser at <code>http://localhost:8080/animals/cats</code>.</p>
<h2 id="handling-requests-where-nothing-matches">Handling requests where nothing matches</h2><br/>
<p>You can use the <code>noMatch</code> method to specify a handler that will be called if nothing matches. If you don't specify a no match handler and nothing matches, a 404 will be returned.</p>
<pre class="prettyprint">routeMatcher.noMatch(new Handler&lt;HttpServerRequest&gt;() {
    public void handle(HttpServerRequest req) {
        req.response().end("Nothing matched");'
    }
});
</pre>
<p><a id="web-sockets"> </a></p>
<h1 id="websockets">WebSockets</h1><br/>
<p><a href="http://en.wikipedia.org/wiki/WebSocket">WebSockets</a> are a web technology that allows a full duplex socket-like connection between HTTP servers and HTTP clients (typically browsers).</p>
<h2 id="websockets-on-the-server">WebSockets on the server</h2><br/>
<p>To use WebSockets on the server you create an HTTP server as normal, but instead of setting a <code>requestHandler</code> you set a <code>websocketHandler</code> on the server.</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.websocketHandler(new Handler&lt;ServerWebSocket&gt;() {
    public void handle(ServerWebSocket ws) {
        // A WebSocket has connected!
    }
}).listen(8080, "localhost");
</pre>
<h3 id="reading-from-and-writing-to-websockets">Reading from and Writing to WebSockets</h3><br/>
<p>The <code>websocket</code> instance passed into the handler implements both <code>ReadStream</code> and <code>WriteStream</code>, so you can read and write data to it in the normal ways. I.e by setting a <code>dataHandler</code> and calling the <code>write</code> method.</p>
<p>See the chapter on <a href="#flow-control">streams and pumps</a> for more information.</p>
<p>For example, to echo all data received on a WebSocket:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.websocketHandler(new Handler&lt;ServerWebSocket&gt;() {
    public void handle(ServerWebSocket ws) {
        Pump.createPump(ws, ws).start();
    }
}).listen(8080, "localhost");
</pre>
<p>The <code>websocket</code> instance also has method <code>writeBinaryFrame</code> for writing binary data. This has the same effect as calling <code>write</code>.</p>
<p>Another method <code>writeTextFrame</code> also exists for writing text data. This is equivalent to calling</p>
<pre class="prettyprint">websocket.write(new Buffer("some-string"));
</pre>
<h3 id="rejecting-websockets">Rejecting WebSockets</h3><br/>
<p>Sometimes you may only want to accept WebSockets which connect at a specific path.</p>
<p>To check the path, you can query the <code>path()</code> method of the websocket. You can then call the <code>reject()</code> method to reject the websocket.</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

server.websocketHandler(new Handler&lt;ServerWebSocket&gt;() {
    public void handle(ServerWebSocket ws) {
        if (ws.path().equals("/services/echo")) {
            Pump.createPump(ws, ws).start();
        } else {
            ws.reject();
        }
    }
}).listen(8080, "localhost");
</pre>
<h3 id="headers-on-the-websocket">Headers on the websocket</h3><br/>
<p>You can use the <code>headers()</code> method to retrieve the headers passed in the Http Request from the client that caused the upgrade to websockets.</p>
<h2 id="websockets-on-the-http-client">WebSockets on the HTTP client</h2><br/>
<p>To use WebSockets from the HTTP client, you create the HTTP client as normal, then call the <code>connectWebsocket</code> function, passing in the URI that you wish to connect to at the server, and a handler.</p>
<p>The handler will then get called if the WebSocket successfully connects. If the WebSocket does not connect - perhaps the server rejects it - then any exception handler on the HTTP client will be called.</p>
<p>Here's an example of WebSocket connection;</p>
<pre class="prettyprint">HttpClient client = vertx.createHttpClient().setHost("foo.com");

client.connectWebsocket("/some-uri", new Handler&lt;WebSocket&gt;() {
    public void handle(WebSocket ws) {
        // Connected!
    }
});
</pre>
<p>Note that the host (and port) is set on the <code>HttpClient</code> instance, and the uri passed in the connect is typically a <em>relative</em> URI.</p>
<p>Again, the client side WebSocket implements <code>ReadStream</code> and <code>WriteStream</code>, so you can read and write to it in the same way as any other stream object.</p>
<h2 id="websockets-in-the-browser">WebSockets in the browser</h2><br/>
<p>To use WebSockets from a compliant browser, you use the standard WebSocket API. Here's some example client side JavaScript which uses a WebSocket.</p>
<pre class="prettyprint">&lt;script&gt;

    var socket = new WebSocket("ws://foo.com/services/echo");

    socket.onmessage = function(event) {
        alert("Received data from websocket: " + event.data);
    }

    socket.onopen = function(event) {
        alert("Web Socket opened");
        socket.send("Hello World");
    };

    socket.onclose = function(event) {
        alert("Web Socket closed");
    };

&lt;/script&gt;
</pre>
<p>For more information see the <a href="http://dev.w3.org/html5/websockets/">WebSocket API documentation</a></p>
<p><a id="sockjs"> </a></p>
<h1 id="sockjs">SockJS</h1><br/>
<p>WebSockets are a new technology, and many users are still using browsers that do not support them, or which support older, pre-final, versions.</p>
<p>Moreover, WebSockets do not work well with many corporate proxies. This means that's it's not possible to guarantee a WebSockets connection is going to succeed for every user.</p>
<p>Enter SockJS.</p>
<p>SockJS is a client side JavaScript library and protocol which provides a simple WebSocket-like interface to the client side JavaScript developer irrespective of whether the actual browser or network will allow real WebSockets.</p>
<p>It does this by supporting various different transports between browser and server, and choosing one at runtime according to browser and network capabilities. All this is transparent to you - you are simply presented with the WebSocket-like interface which <em>just works</em>.</p>
<p>Please see the <a href="https://github.com/sockjs/sockjs-client">SockJS website</a> for more information.</p>
<h2 id="sockjs-server">SockJS Server</h2><br/>
<p>Vert.x provides a complete server side SockJS implementation.</p>
<p>This enables Vert.x to be used for modern, so-called <em>real-time</em> (this is the <em>modern</em> meaning of <em>real-time</em>, not to be confused by the more formal pre-existing definitions of soft and hard real-time systems) web applications that push data to and from rich client-side JavaScript applications, without having to worry about the details of the transport.</p>
<p>To create a SockJS server you simply create a HTTP server as normal and then call the <code>createSockJSServer</code> method of your <code>vertx</code> instance passing in the Http server:</p>
<pre class="prettyprint">HttpServer httpServer = vertx.createHttpServer();

SockJSServer sockJSServer = vertx.createSockJSServer(httpServer);
</pre>
<p>Each SockJS server can host multiple <em>applications</em>.</p>
<p>Each application is defined by some configuration, and provides a handler which gets called when incoming SockJS connections arrive at the server.</p>
<p>For example, to create a SockJS echo application:</p>
<pre class="prettyprint">HttpServer httpServer = vertx.createHttpServer();

SockJSServer sockJSServer = vertx.createSockJSServer(httpServer);

JsonObject config = new JsonObject().putString("prefix", "/echo");

sockJSServer.installApp(config, new Handler&lt;SockJSSocket&gt;() {
    public void handle(SockJSSocket sock) {
        Pump.createPump(sock, sock).start();
    }
});

httpServer.listen(8080);
</pre>
<p>The configuration is an instance of <code>org.vertx.java.core.json.JsonObject</code>, which takes the following fields:</p>
<ul>
<li><code>prefix</code>: A url prefix for the application. All http requests whose paths begins with selected prefix will be handled by the application. This property is mandatory.</li>
<li><code>insert_JSESSIONID</code>: Some hosting providers enable sticky sessions only to requests that have JSESSIONID cookie set. This setting controls if the server should set this cookie to a dummy value. By default setting JSESSIONID cookie is enabled. More sophisticated beaviour can be achieved by supplying a function.</li>
<li><code>session_timeout</code>: The server sends a <code>close</code> event when a client receiving connection have not been seen for a while. This delay is configured by this setting. By default the <code>close</code> event will be emitted when a receiving connection wasn't seen for 5 seconds.</li>
<li><code>heartbeat_period</code>: In order to keep proxies and load balancers from closing long running http requests we need to pretend that the connecion is active and send a heartbeat packet once in a while. This setting controlls how often this is done. By default a heartbeat packet is sent every 5 seconds.</li>
<li><code>max_bytes_streaming</code>: Most streaming transports save responses on the client side and don't free memory used by delivered messages. Such transports need to be garbage-collected once in a while. <code>max_bytes_streaming</code> sets a minimum number of bytes that can be send over a single http streaming request before it will be closed. After that client needs to open new request. Setting this value to one effectively disables streaming and will make streaming transports to behave like polling transports. The default value is 128K.</li>
<li><code>library_url</code>: Transports which don't support cross-domain communication natively ('eventsource' to name one) use an iframe trick. A simple page is served from the SockJS server (using its foreign domain) and is placed in an invisible iframe. Code run from this iframe doesn't need to worry about cross-domain issues, as it's being run from domain local to the SockJS server. This iframe also does need to load SockJS javascript client library, and this option lets you specify its url (if you're unsure, point it to the latest minified SockJS client release, this is the default). The default value is <code>http://cdn.sockjs.org/sockjs-0.3.4.min.js</code></li>
</ul>
<h2 id="reading-and-writing-data-from-a-sockjs-server">Reading and writing data from a SockJS server</h2><br/>
<p>The <code>SockJSSocket</code> object passed into the SockJS handler implements <code>ReadStream</code> and <code>WriteStream</code> much like <code>NetSocket</code> or <code>WebSocket</code>. You can therefore use the standard API for reading and writing to the SockJS socket or using it in pumps.</p>
<p>See the chapter on <a href="#flow-control">Streams and Pumps</a> for more information.</p>
<h2 id="sockjs-client">SockJS client</h2><br/>
<p>For full information on using the SockJS client library please see the SockJS website. A simple example:</p>
<pre class="prettyprint">&lt;script&gt;
   var sock = new SockJS('http://mydomain.com/my_prefix');

   sock.onopen = function() {
       console.log('open');
   };

   sock.onmessage = function(e) {
       console.log('message', e.data);
   };

   sock.onclose = function() {
       console.log('close');
   };
&lt;/script&gt;
</pre>
<p>As you can see the API is very similar to the WebSockets API.</p>
<h1 id="sockjs-eventbus-bridge">SockJS - EventBus Bridge</h1><br/>
<h2 id="setting-up-the-bridge">Setting up the Bridge</h2><br/>
<p>By connecting up SockJS and the Vert.x event bus we create a distributed event bus which not only spans multiple Vert.x
 instances on the server side, but can also include client side JavaScript running in browsers.</p>
<p>We can therefore create a huge distributed bus encompassing many browsers and servers. The browsers don't have to be connected to the same server as long as the servers are connected.</p>
<p>On the server side we have already discussed the event bus API.</p>
<p>We also provide a client side JavaScript library called <code>vertxbus.js</code> which provides the same event bus API, but on the client side.</p>
<p>This library internally uses SockJS to send and receive data to a SockJS Vert.x server called the SockJS bridge. It's the bridge's responsibility to bridge data between SockJS sockets and the event bus on the server side.</p>
<p>Creating a Sock JS bridge is simple. You just call the <code>bridge</code> method on the SockJS server.</p>
<p>You will also need to secure the bridge (see below).</p>
<p>The following example bridges the event bus to client side JavaScript:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

JsonObject config = new JsonObject().putString("prefix", "/eventbus");

JsonArray noPermitted = new JsonArray();
noPermitted.add(new JsonObject());

vertx.createSockJSServer(server).bridge(config, noPermitted, noPermitted);

server.listen(8080);
</pre>
<p>To let all messages through you can specify two JSON array with a single empty JSON object which will match all messages.</p>
<p><strong>Be very careful!</strong></p>
<h2 id="using-the-event-bus-from-client-side-javascript">Using the Event Bus from client side JavaScript</h2><br/>
<p>Once you've set up a bridge, you can use the event bus from the client side as follows:</p>
<p>In your web page, you need to load the script <code>vertxbus.js</code>, then you can access the Vert.x event bus API. Here's a rough idea of how to use it. For a full working examples, please consult the vert.x examples.</p>
<pre class="prettyprint">&lt;script src="http://cdn.sockjs.org/sockjs-0.3.4.min.js"&gt;&lt;/script&gt;
&lt;script src='vertxbus.js'&gt;&lt;/script&gt;

&lt;script&gt;

    var eb = new vertx.EventBus('http://localhost:8080/eventbus');

    eb.onopen = function() {

      eb.registerHandler('some-address', function(message) {

        console.log('received a message: ' + JSON.stringify(message);

      });

      eb.send('some-address', {name: 'tim', age: 587});

    }

&lt;/script&gt;
</pre>
<p>You can find <code>vertxbus.js</code> in the <code>client</code> directory of the Vert.x distribution.</p>
<p>The first thing the example does is to create a instance of the event bus</p>
<pre class="prettyprint">var eb = new vertx.EventBus('http://localhost:8080/eventbus');
</pre>
<p>The parameter to the constructor is the URI where to connect to the event bus. Since we create our bridge with the prefix <code>eventbus</code> we will connect there.</p>
<p>You can't actually do anything with the bridge until it is opened. When it is open the <code>onopen</code> handler will be called.</p>
<p>The client side event bus API for registering and unregistering handlers and for sending messages is the same as the server side one. Please consult the chapter on the event bus for full information.</p>
<p><strong>There is one more thing to do before getting this working, please read the following section....</strong></p>
<h2 id="securing-the-bridge">Securing the Bridge</h2><br/>
<p>If you started a bridge like in the above example without securing it, and attempted to send messages through it you'd find that the messages mysteriously disappeared. What happened to them?</p>
<p>For most applications you probably don't want client side JavaScript being able to send just any message to any verticle on the server side or to all other browsers.</p>
<p>For example, you may have a persistor verticle on the event bus which allows data to be accessed or deleted. We don't want badly behaved or malicious clients being able to delete all the data in your database! Also, we don't necessarily want any client to be able to listen in on any topic.</p>
<p>To deal with this, a SockJS bridge will, by default refuse to let through any messages. It's up to you to tell the bridge what messages are ok for it to pass through. (There is an exception for reply messages which are always allowed through).</p>
<p>In other words the bridge acts like a kind of firewall which has a default <em>deny-all</em> policy.</p>
<p>Configuring the bridge to tell it what messages it should pass through is easy. You pass in two Json arrays that represent <em>matches</em>, as arguments to <code>bridge</code>.</p>
<p>The first array is the <em>inbound</em> list and represents the messages that you want to allow through from the client to the server. The second array is the <em>outbound</em> list and represents the messages that you want to allow through from the server to the client.</p>
<p>Each match can have up to three fields:</p>
<ol>
<li><code>address</code>: This represents the exact address the message is being sent to. If you want to filter messages based on an exact address you use this field.</li>
<li><code>address_re</code>: This is a regular expression that will be matched against the address. If you want to filter messages based on a regular expression you use this field. If the <code>address</code> field is specified this field will be ignored.</li>
<li><code>match</code>: This allows you to filter messages based on their structure. Any fields in the match must exist in the message with the same values for them to be passed. This currently only works with JSON messages.</li>
</ol>
<p>When a message arrives at the bridge, it will look through the available permitted entries.</p>
<ul>
<li>
<p>If an <code>address</code> field has been specified then the <code>address</code> must match exactly with the address of the message for it to be considered matched.</p>
</li>
<li>
<p>If an <code>address</code> field has not been specified and an <code>address_re</code> field has been specified then the regular expression in <code>address_re</code> must match with the address of the message for it to be considered matched.</p>
</li>
<li>
<p>If a <code>match</code> field has been specified, then also the structure of the message must match.</p>
</li>
</ul>
<p>Here is an example:</p>
<pre class="prettyprint">HttpServer server = vertx.createHttpServer();

JsonObject config = new JsonObject().putString("prefix", "/echo");

JsonArray inboundPermitted = new JsonArray();

// Let through any messages sent to 'demo.orderMgr'
JsonObject inboundPermitted1 = new JsonObject().putString("address", "demo.orderMgr");
inboundPermitted.add(inboundPermitted1);

// Allow calls to the address 'demo.persistor' as long as the messages
// have an action field with value 'find' and a collection field with value
// 'albums'
JsonObject inboundPermitted2 = new JsonObject().putString("address", "demo.persistor")
    .putObject("match", new JsonObject().putString("action", "find")
                                        .putString("collection", "albums"));
inboundPermitted.add(inboundPermitted2);

// Allow through any message with a field `wibble` with value `foo`.
JsonObject inboundPermitted3 = new JsonObject().putObject("match", new JsonObject().putString("wibble", "foo"));
inboundPermitted.add(inboundPermitted3);

JsonArray outboundPermitted = new JsonArray();

// Let through any messages coming from address 'ticker.mystock'
JsonObject outboundPermitted1 = new JsonObject().putString("address", "ticker.mystock");
outboundPermitted.add(outboundPermitted1);

// Let through any messages from addresses starting with "news." (e.g. news.europe, news.usa, etc)
JsonObject outboundPermitted2 = new JsonObject().putString("address_re", "news\\..+");
outboundPermitted.add(outboundPermitted2);

vertx.createSockJSBridge(server).bridge(config, inboundPermitted, outboundPermitted);

server.listen(8080);
</pre>
<h2 id="messages-that-require-authorisation">Messages that require authorisation</h2><br/>
<p>The bridge can also refuse to let certain messages through if the user is not authorised.</p>
<p>To enable this you need to make sure an instance of the <code>vertx.auth-mgr</code> module is available on the event bus. (Please see the modules manual for a full description of modules).</p>
<p>To tell the bridge that certain messages require authorisation before being passed, you add the field <code>requires_auth</code> with the value of <code>true</code> in the match. The default value is <code>false</code>. For example, the following match:</p>
<pre class="prettyprint">{
  address : 'demo.persistor',
  match : {
    action : 'find',
    collection : 'albums'
  },
  requires_auth: true
}
</pre>
<p>This tells the bridge that any messages to save orders in the <code>orders</code> collection, will only be passed if the user is successful authenticated (i.e. logged in ok) first.</p>
<h1 id="file-system">File System</h1><br/>
<p>Vert.x lets you manipulate files on the file system. File system operations are asynchronous and take a handler function as the last argument. This function will be called when the operation is complete, or an error has occurred.</p>
<p>The argument passed into the handler is an instance of <code>org.vertx.java.core.AsyncResult</code>.</p>
<h2 id="synchronous-forms">Synchronous forms</h2><br/>
<p>For convenience, we also provide synchronous forms of most operations. It's highly recommended the asynchronous forms are always used for real applications.</p>
<p>The synchronous form does not take a handler as an argument and returns its results directly. The name of the synchronous function is the same as the name as the asynchronous form with <code>Sync</code> appended.</p>
<h2 id="copy">copy</h2><br/>
<p>Copies a file.</p>
<p>This function can be called in two different ways:</p>
<ul>
<li><code>copy(source, destination, handler)</code></li>
</ul>
<p>Non recursive file copy. <code>source</code> is the source file name. <code>destination</code> is the destination file name.</p>
<p>Here's an example:</p>
<pre class="prettyprint">vertx.fileSystem().copy("foo.dat", "bar.dat", new AsyncResultHandler&lt;Void&gt;() {
    public void handle(AsyncResult ar) {
        if (ar.succeeded()) {
            log.info("Copy was successful");
        } else {
            log.error("Failed to copy", ar.cause());
        }
    }
});
</pre>
<ul>
<li><code>copy(source, destination, recursive, handler)</code></li>
</ul>
<p>Recursive copy. <code>source</code> is the source file name. <code>destination</code> is the destination file name. <code>recursive</code> is a boolean flag - if <code>true</code> and source is a directory, then a recursive copy of the directory and all its contents will be attempted.</p>
<h2 id="move">move</h2><br/>
<p>Moves a file.</p>
<p><code>move(source, destination, handler)</code></p>
<p><code>source</code> is the source file name. <code>destination</code> is the destination file name.</p>
<h2 id="truncate">truncate</h2><br/>
<p>Truncates a file.</p>
<p><code>truncate(file, len, handler)</code></p>
<p><code>file</code> is the file name of the file to truncate. <code>len</code> is the length in bytes to truncate it to.</p>
<h2 id="chmod">chmod</h2><br/>
<p>Changes permissions on a file or directory.</p>
<p>This function can be called in two different ways:</p>
<ul>
<li><code>chmod(file, perms, handler)</code>.</li>
</ul>
<p>Change permissions on a file.</p>
<p><code>file</code> is the file name. <code>perms</code> is a Unix style permissions string made up of 9 characters. The first three are the owner's permissions. The second three are the group's permissions and the third three are others permissions. In each group of three if the first character is <code>r</code> then it represents a read permission. If the second character is <code>w</code>  it represents write permission. If the third character is <code>x</code> it represents execute permission. If the entity does not have the permission the letter is replaced with <code>-</code>. Some examples:</p>
<pre class="prettyprint">rwxr-xr-x
r--r--r--
</pre>
<ul>
<li><code>chmod(file, perms, dirPerms, handler)</code>.</li>
</ul>
<p>Recursively change permissionson a directory. <code>file</code> is the directory name. <code>perms</code> is a Unix style permissions to apply recursively to any files in the directory. <code>dirPerms</code> is a Unix style permissions string to apply to the directory and any other child directories recursively.</p>
<h2 id="props">props</h2><br/>
<p>Retrieve properties of a file.</p>
<p><code>props(file, handler)</code></p>
<p><code>file</code> is the file name. The props are returned in the handler. The results is an object with the following methods:</p>
<ul>
<li><code>creationTime()</code>: Time of file creation.</li>
<li><code>lastAccessTime()</code>: Time of last file access.</li>
<li><code>lastModifiedTime()</code>: Time file was last modified.</li>
<li><code>isDirectory()</code>: This will have the value <code>true</code> if the file is a directory.</li>
<li><code>isRegularFile()</code>: This will have the value <code>true</code> if the file is a regular file (not symlink or directory).</li>
<li><code>isSymbolicLink()</code>: This will have the value <code>true</code> if the file is a symbolic link.</li>
<li><code>isOther()</code>: This will have the value <code>true</code> if the file is another type.</li>
</ul>
<p>Here's an example:</p>
<pre class="prettyprint">vertx.fileSystem().props("foo.dat", "bar.dat", new AsyncResultHandler&lt;FileProps&gt;() {
    public void handle(AsyncResult&lt;FileProps&gt; ar) {
        if (ar.succeeded()) {
            log.info("File props are:");
            log.info("Last accessed: " + ar.result().lastAccessTime());
            // etc
        } else {
            log.error("Failed to get props", ar.cause());
        }
    }
});
</pre>
<h2 id="lprops">lprops</h2><br/>
<p>Retrieve properties of a link. This is like <code>props</code> but should be used when you want to retrieve properties of a link itself without following it.</p>
<p>It takes the same arguments and provides the same results as <code>props</code>.</p>
<h2 id="link">link</h2><br/>
<p>Create a hard link.</p>
<p><code>link(link, existing, handler)</code></p>
<p><code>link</code> is the name of the link. <code>existing</code> is the exsting file (i.e. where to point the link at).</p>
<h2 id="symlink">symlink</h2><br/>
<p>Create a symbolic link.</p>
<p><code>symlink(link, existing, handler)</code></p>
<p><code>link</code> is the name of the symlink. <code>existing</code> is the exsting file (i.e. where to point the symlink at).</p>
<h2 id="unlink">unlink</h2><br/>
<p>Unlink (delete) a link.</p>
<p><code>unlink(link, handler)</code></p>
<p><code>link</code> is the name of the link to unlink.</p>
<h2 id="readsymlink">readSymLink</h2><br/>
<p>Reads a symbolic link. I.e returns the path representing the file that the symbolic link specified by <code>link</code> points to.</p>
<p><code>readSymLink(link, handler)</code></p>
<p><code>link</code> is the name of the link to read. An usage example would be:</p>
<pre class="prettyprint">vertx.fileSystem().readSymLink("somelink", new AsyncResultHandler&lt;String&gt;() {
    public void handle(AsyncResult&lt;String&gt; ar) {
        if (ar.succeeded()) {
            log.info("Link points at  " + ar.result());
        } else {
            log.error("Failed to read", ar.cause());
        }
    }
});
</pre>
<h2 id="delete">delete</h2><br/>
<p>Deletes a file or recursively deletes a directory.</p>
<p>This function can be called in two ways:</p>
<ul>
<li><code>delete(file, handler)</code></li>
</ul>
<p>Deletes a file. <code>file</code> is the file name.</p>
<ul>
<li><code>delete(file, recursive, handler)</code></li>
</ul>
<p>If <code>recursive</code> is <code>true</code>, it deletes a directory with name <code>file</code>, recursively. Otherwise it just deletes a file.</p>
<h2 id="mkdir">mkdir</h2><br/>
<p>Creates a directory.</p>
<p>This function can be called in three ways:</p>
<ul>
<li><code>mkdir(dirname, handler)</code></li>
</ul>
<p>Makes a new empty directory with name <code>dirname</code>, and default permissions `</p>
<ul>
<li><code>mkdir(dirname, createParents, handler)</code></li>
</ul>
<p>If <code>createParents</code> is <code>true</code>, this creates a new directory and creates any of its parents too. Here's an example</p>
<pre class="prettyprint">vertx.fileSystem().mkdir("a/b/c", true, new AsyncResultHandler&lt;Void&gt;() {
    public void handle(AsyncResult ar) {
        if (ar.suceeded()) {
            log.info("Directory created ok");
        } else {
            log.error("Failed to mkdir", ar.cause());
        }
    }
});
</pre>
<ul>
<li><code>mkdir(dirname, createParents, perms, handler)</code></li>
</ul>
<p>Like <code>mkdir(dirname, createParents, handler)</code>, but also allows permissions for the newly created director(ies) to be specified. <code>perms</code> is a Unix style permissions string as explained earlier.</p>
<h2 id="readdir">readDir</h2><br/>
<p>Reads a directory. I.e. lists the contents of the directory.</p>
<p>This function can be called in two ways:</p>
<ul>
<li><code>readDir(dirName)</code></li>
</ul>
<p>Lists the contents of a directory</p>
<ul>
<li><code>readDir(dirName, filter)</code></li>
</ul>
<p>List only the contents of a directory which match the filter. Here's an example which only lists files with an extension <code>txt</code> in a directory.</p>
<pre class="prettyprint">vertx.fileSystem().readDir("mydirectory", ".*\\.txt", new AsyncResultHandler&lt;String[]&gt;() {
    public void handle(AsyncResult&lt;String[]&gt; ar) {
        if (ar.succeeded() {
            log.info("Directory contains these .txt files");
            for (int i = 0; i &lt; ar.result().length; i++) {
              log.info(ar.result()[i]);
            }
        } else {
            log.error("Failed to read", ar.cause());
        }
    }
});
</pre>
<p>The filter is a regular expression.</p>
<h2 id="readfile">readFile</h2><br/>
<p>Read the entire contents of a file in one go. <em>Be careful if using this with large files since the entire file will be stored in memory at once</em>.</p>
<p><code>readFile(file)</code>. Where <code>file</code> is the file name of the file to read.</p>
<p>The body of the file will be returned as an instance of <code>org.vertx.java.core.buffer.Buffer</code> in the handler.</p>
<p>Here is an example:</p>
<pre class="prettyprint">vertx.fileSystem().readFile("myfile.dat", new AsyncResultHandler&lt;Buffer&gt;() {
    public void handle(AsyncResult&lt;Buffer&gt; ar) {
        if (ar.succeeded()) {
            log.info("File contains: " + ar.result().length() + " bytes");
        } else {
            log.error("Failed to read", ar.cause());
        }
    }
});
</pre>
<h2 id="writefile">writeFile</h2><br/>
<p>Writes an entire <code>Buffer</code> or a string into a new file on disk.</p>
<p><code>writeFile(file, data, handler)</code> Where <code>file</code> is the file name. <code>data</code> is a <code>Buffer</code> or string.</p>
<h2 id="createfile">createFile</h2><br/>
<p>Creates a new empty file.</p>
<p><code>createFile(file, handler)</code>. Where <code>file</code> is the file name.</p>
<h2 id="exists">exists</h2><br/>
<p>Checks if a file exists.</p>
<p><code>exists(file, handler)</code>. Where <code>file</code> is the file name.</p>
<p>The result is returned in the handler.</p>
<pre class="prettyprint">vertx.fileSystem().exists("some-file.txt", new AsyncResultHandler&lt;Boolean&gt;() {
    public void handle(AsyncResult&lt;Boolean&gt; ar) {
        if (ar.succeeded()) {
            log.info("File " + (ar.result() ? "exists" : "does not exist"));
        } else {
            log.error("Failed to check existence", ar.cause());
        }
    }
});
</pre>
<h2 id="fsprops">fsProps</h2><br/>
<p>Get properties for the file system.</p>
<p><code>fsProps(file, handler)</code>. Where <code>file</code> is any file on the file system.</p>
<p>The result is returned in the handler. The result object is an instance of <code>org.vertx.java.core.file.FileSystemProps</code> has the following methods:</p>
<ul>
<li><code>totalSpace()</code>: Total space on the file system in bytes.</li>
<li><code>unallocatedSpace()</code>: Unallocated space on the file system in bytes.</li>
<li><code>usableSpace()</code>: Usable space on the file system in bytes.</li>
</ul>
<p>Here is an example:</p>
<pre class="prettyprint">vertx.fileSystem().fsProps("mydir", new AsyncResultHandler&lt;FileSystemProps&gt;() {
    public void handle(AsyncResult&lt;FileSystemProps&gt; ar) {
        if (ar.succeeded()) {
            log.info("total space: " + ar.result().totalSpace());
            // etc
        } else {
            log.error("Failed to check existence", ar.cause());
        }
    }
});
</pre>
<h2 id="open">open</h2><br/>
<p>Opens an asynchronous file for reading \ writing.</p>
<p>This function can be called in four different ways:</p>
<ul>
<li><code>open(file, handler)</code></li>
</ul>
<p>Opens a file for reading and writing. <code>file</code> is the file name. It creates it if it does not already exist.</p>
<ul>
<li><code>open(file, perms, handler)</code></li>
</ul>
<p>Opens a file for reading and writing. <code>file</code> is the file name. It creates it if it does not already exist and assigns it the permissions as specified by <code>perms</code>.</p>
<ul>
<li><code>open(file, perms, createNew, handler)</code></li>
</ul>
<p>Opens a file for reading and writing. <code>file</code> is the file name. It <code>createNew</code> is <code>true</code> it creates it if it does not already exist.</p>
<ul>
<li><code>open(file, perms, read, write, createNew, handler)</code></li>
</ul>
<p>Opens a file. <code>file</code> is the file name. If <code>read</code> is <code>true</code> it is opened for reading. If <code>write</code> is <code>true</code> it is opened for writing. It <code>createNew</code> is <code>true</code> it creates it if it does not already exist.</p>
<ul>
<li><code>open(file, perms, read, write, createNew, flush, handler)</code></li>
</ul>
<p>Opens a file. <code>file</code> is the file name. If <code>read</code> is <code>true</code> it is opened for reading. If <code>write</code> is <code>true</code> it is opened for writing. It <code>createNew</code> is <code>true</code> it creates it if it does not already exist. If <code>flush</code> is <code>true</code> all writes are immediately flushed through the OS cache (default value of <code>flush</code> is false).</p>
<p>When the file is opened, an instance of <code>org.vertx.java.core.file.AsyncFile</code> is passed into the result handler:</p>
<pre class="prettyprint">vertx.fileSystem().open("some-file.dat", new AsyncResultHandler&lt;AsyncFile&gt;() {
    public void handle(AsyncResult&lt;AsyncFile&gt; ar) {
        if (ar.succeeded()) {
            log.info("File opened ok!");
            // etc
        } else {
            log.error("Failed to open file", ar.cause());
        }
    }
});
</pre>
<h2 id="asyncfile">AsyncFile</h2><br/>
<p>Instances of <code>org.vertx.java.core.file.AsyncFile</code> are returned from calls to <code>open</code> and you use them to read from and write to files asynchronously. They allow asynchronous random file access.</p>
<p><code>AsyncFile</code> implements<code>ReadStream</code> and <code>WriteStream</code> so you can pump files to and from other stream objects such as net sockets, http requests and responses, and WebSockets.</p>
<p>They also allow you to read and write directly to them.</p>
<h3 id="random-access-writes">Random access writes</h3><br/>
<p>To use an <code>AsyncFile</code> for random access writing you use the <code>write</code> method.</p>
<p><code>write(buffer, position, handler)</code>.</p>
<p>The parameters to the method are:</p>
<ul>
<li><code>buffer</code>: the buffer to write.</li>
<li><code>position</code>: an integer position in the file where to write the buffer. If the position is greater or equal to the size of the file, the file will be enlarged to accomodate the offset.</li>
</ul>
<p>Here is an example of random access writes:</p>
<pre class="prettyprint">vertx.fileSystem().open("some-file.dat", new AsyncResultHandler&lt;AsyncFile&gt;() {
    public void handle(AsyncResult&lt;AsyncFile&gt; ar) {
        if (ar.succeeded()) {
            AsyncFile asyncFile = ar.result();
            // File open, write a buffer 5 times into a file
            Buffer buff = new Buffer("foo");
            for (int i = 0; i &lt; 5; i++) {
                asyncFile.write(buff, buff.length() * i, new AsyncResultHandler&lt;Void&gt;() {
                    public void handle(AsyncResult ar) {
                        if (ar.succeeded()) {
                            log.info("Written ok!");
                            // etc
                        } else {
                            log.error("Failed to write", ar.cause());
                        }
                    }
                });
            }
        } else {
            log.error("Failed to open file", ar.cause());
        }
    }
});
</pre>
<h3 id="random-access-reads">Random access reads</h3><br/>
<p>To use an <code>AsyncFile</code> for random access reads you use the <code>read</code> method.</p>
<p><code>read(buffer, offset, position, length, handler)</code>.</p>
<p>The parameters to the method are:</p>
<ul>
<li><code>buffer</code>: the buffer into which the data will be read.</li>
<li><code>offset</code>: an integer offset into the buffer where the read data will be placed.</li>
<li><code>position</code>: the position in the file where to read data from.</li>
<li><code>length</code>: the number of bytes of data to read</li>
</ul>
<p>Here's an example of random access reads:</p>
<pre class="prettyprint">vertx.fileSystem().open("some-file.dat", new AsyncResultHandler&lt;AsyncFile&gt;() {
    public void handle(AsyncResult&lt;AsyncFile&gt; ar) {
        if (ar.succeeded()) {
            AsyncFile asyncFile = ar.result();
            Buffer buff = new Buffer(1000);
            for (int i = 0; i &lt; 10; i++) {
                asyncFile.read(buff, i * 100, i * 100, 100, new AsyncResultHandler&lt;Buffer&gt;() {
                    public void handle(AsyncResult&lt;Buffer&gt; ar) {
                        if (ar.succeeded()) {
                            log.info("Read ok!");
                            // etc
                        } else {
                            log.error("Failed to write", ar.cause());
                        }
                    }
                });
            }
        } else {
            log.error("Failed to open file", ar.cause());
        }
    }
});
</pre>
<p>If you attempt to read past the end of file, the read will not fail but it will simply read zero bytes.</p>
<h3 id="flushing-data-to-underlying-storage">Flushing data to underlying storage.</h3><br/>
<p>If the <code>AsyncFile</code> was not opened with <code>flush = true</code>, then you can manually flush any writes from the OS cache by calling the <code>flush()</code> method.</p>
<p>This method can also be called with an handler which will be called when the flush is complete.</p>
<h3 id="using-asyncfile-as-readstream-and-writestream">Using AsyncFile as <code>ReadStream</code> and <code>WriteStream</code></h3><br/>
<p><code>AsyncFile</code> implements <code>ReadStream</code> and <code>WriteStream</code>. You can then use them with a pump to pump data to and from other read and write streams.</p>
<p>Here's an example of pumping data from a file on a client to a HTTP request:</p>
<pre class="prettyprint">final HttpClient client = vertx.createHttpClient.setHost("foo.com");

vertx.fileSystem().open("some-file.dat", new AsyncResultHandler&lt;AsyncFile&gt;() {
    public void handle(AsyncResult&lt;AsyncFile&gt; ar) {
        if (ar.succeeded()) {
            final HttpClientRequest request = client.put("/uploads", new Handler&lt;HttpClientResponse&gt;() {
                public void handle(HttpClientResponse resp) {
                    log.info("Received response: " + resp.statusCode());
                }
            });
            AsyncFile asyncFile = ar.result();
            request.setChunked(true);
            Pump.createPump(asyncFile, request).start();
            asyncFile.endHandler(new VoidHandler() {
                public void handle() {
                    // File sent, end HTTP requuest
                    request.end();
                }
            });
        } else {
            log.error("Failed to open file", ar.cause());
        }
    }
});
</pre>
<h3 id="closing-an-asyncfile">Closing an AsyncFile</h3><br/>
<p>To close an <code>AsyncFile</code> call the <code>close()</code> method. Closing is asynchronous and if you want to be notified when the close has been completed you can specify a handler function as an argument.</p>
<h1 id="dns-client">DNS Client</h1><br/>
<p>Often you will find yourself in situations where you need to obtain DNS informations in an asynchronous fashion. Unfortunally this is not possible with the API that is shipped with Java itself. Because of this Vert.x offers it's own API for DNS resolution which is fully asynchronous.</p>
<p>To obtain a DnsClient instance you will create a new via the Vertx instance.</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53), new InetSocketAddress("10.0.0.2", 53));
</pre>
<p>Be aware that you can pass in a varargs of InetSocketAddress arguments to specifiy more then one DNS Server to try to query for DNS resolution. The DNS Servers will be queried in the same order as specified here. Where the next will be used once the first produce an error while be used.</p>
<h2 id="lookup">lookup</h2><br/>
<p>Try to lookup the A (ipv4) or AAAA (ipv6) record for a given name. The first which is returned will be used, so it behaves the same way as you may be used from when using "nslookup" on your operation system.</p>
<p>To lookup the A / AAAA record for "vertx.io" you would typically use it like:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.lookup("vertx.io", new AsyncResultHandler&lt;InetAddress&gt;() {
    public void handle(AsyncResult&lt;InetAddress&gt; ar) {
        if (ar.succeeded()) {
            System.out.println(ar.result());
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<p>Be aware that it either would use an Inet4Address or Inet6Address in the AsyncResult depending on if an A or AAAA record was resolved.</p>
<h2 id="lookup4">lookup4</h2><br/>
<p>Try to lookup the A (ipv4) record for a given name. The first which is returned will be used, so it behaves the same way as you may be used from when using "nslookup" on your operation system.</p>
<p>To lookup the A record for "vertx.io" you would typically use it like:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.lookup4("vertx.io", new AsyncResultHandler&lt;Inet4Address&gt;() {
    public void handle(AsyncResult&lt;Inet4Address&gt; ar) {
        if (ar.succeeded()) {
            System.out.println(ar.result());
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<p>As it only resolves A records and so is ipv4 only it will use Inet4Address as result.</p>
<h2 id="lookup6">lookup6</h2><br/>
<p>Try to lookup the AAAA (ipv5) record for a given name. The first which is returned will be used, so it behaves the same way as you may be used from when using "nslookup" on your operation system.</p>
<p>To lookup the A record for "vertx.io" you would typically use it like:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.lookup6("vertx.io", new AsyncResultHandler&lt;Inet6Address&gt;() {
    public void handle(AsyncResult&lt;Inet6Address&gt; ar) {
        if (ar.succeeded()) {
            System.out.println(ar.result());
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<p>As it only resolves AAAA records and so is ipv6 only it will use Inet6Address as result.</p>
<h2 id="resolvea">resolveA</h2><br/>
<p>Try to resolve all A (ipv4) records for a given name. This is quite similar to using "dig" on unix like operation systems.</p>
<p>To lookup all the A records for "vertx.io" you would typically do:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.resolveA("vertx.io", new AsyncResultHandler&lt;List&lt;Inet4Address&gt;&gt;() {
    public void handle(AsyncResult&lt;List&lt;Inet4Address&gt;&gt; ar) {
        if (ar.succeeded()) {
            List&lt;Inet4Address&gt; records = ar.result());
            for (Inet4Address record: records) {
                System.out.println(record);
            }
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<p>As it only resolves A records and so is ipv4 only it will use Inet4Address as result.</p>
<h2 id="resolveaaaa">resolveAAAA</h2><br/>
<p>Try to resolve all AAAA (ipv6) records for a given name. This is quite similar to using "dig" on unix like operation systems.</p>
<p>To lookup all the AAAAA records for "vertx.io" you would typically do:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.resolveAAAA("vertx.io", new AsyncResultHandler&lt;List&lt;Inet6Address&gt;&gt;() {
    public void handle(AsyncResult&lt;List&lt;Inet6Address&gt;&gt; ar) {
        if (ar.succeeded()) {
            List&lt;Inet6Address&gt; records = ar.result());
            for (Inet6Address record: records) {
                System.out.println(record);
            }
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<p>As it only resolves AAAA records and so is ipv6 only it will use Inet6Address as result.</p>
<h2 id="resolvecname">resolveCNAME</h2><br/>
<p>Try to resolve all CNAME records for a given name. This is quite similar to using "dig" on unix like operation systems.</p>
<p>To lookup all the CNAME records for "vertx.io" you would typically do:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.resolveCNAME("vertx.io", new AsyncResultHandler&lt;List&lt;String&gt;&gt;() {
    public void handle(AsyncResult&lt;List&lt;String&gt;&gt; ar) {
        if (ar.succeeded()) {
            List&lt;String&gt; records = ar.result());
            for (String record: records) {
                System.out.println(record);
            }
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<h2 id="resolvemx">resolveMX</h2><br/>
<p>Try to resolve all MX records for a given name. The MX records are used to define which Mail-Server accepts emails for a given domain.</p>
<p>To lookup all the MX records for "vertx.io" you would typically do:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.resolveMX("vertx.io", new AsyncResultHandler&lt;List&lt;MxRecord&gt;&gt;() {
    public void handle(AsyncResult&lt;List&lt;MxRecord&gt;&gt; ar) {
        if (ar.succeeded()) {
            List&lt;MxRecord&gt; records = ar.result());
            for (MxRecord record: records) {
                System.out.println(record);
            }
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<p>Be aware that the List will contain the MxRecords sorted by the priority of them, which means MxRecords with smaller priority coming first in the List.</p>
<p>The MxRecord allows you to access the priority and the name of the MX record by offer methods for it like:</p>
<pre class="prettyprint">MxRecord record = ...
record.priority();
record.name();
</pre>
<h2 id="resolvetxt">resolveTXT</h2><br/>
<p>Try to resolve all TXT records for a given name. TXT records are often used to define extra informations for a domain.</p>
<p>To resolve all the TXT records for "vertx.io" you could use something along these lines:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.resolveTXT("vertx.io", new AsyncResultHandler&lt;List&lt;String&gt;&gt;() {
    public void handle(AsyncResult&lt;List&lt;String&gt;&gt; ar) {
        if (ar.succeeded()) {
            List&lt;String&gt; records = ar.result());
            for (String record: records) {
                System.out.println(record);
            }
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<h2 id="resolvens">resolveNS</h2><br/>
<p>Try to resolve all NS records for a given name. The NS records specify which DNS Server hosts the DNS informations for a given domain.</p>
<p>To resolve all the NS records for "vertx.io" you could use something along these lines:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.resolveNS("vertx.io", new AsyncResultHandler&lt;List&lt;String&gt;&gt;() {
    public void handle(AsyncResult&lt;List&lt;String&gt;&gt; ar) {
        if (ar.succeeded()) {
            List&lt;String&gt; records = ar.result());
            for (String record: records) {
                System.out.println(record);
            }
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<h2 id="resolvesrv">resolveSRV</h2><br/>
<p>Try to resolve all SRV records for a given name. The SRV records are used to define extra informations like port and hostname of services. Some protocols need this extra informations.</p>
<p>To lookup all the SRV records for "vertx.io" you would typically do:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.resolveMX("vertx.io", new AsyncResultHandler&lt;List&lt;SrvRecord&gt;&gt;() {
    public void handle(AsyncResult&lt;List&lt;SrvRecord&gt;&gt; ar) {
        if (ar.succeeded()) {
            List&lt;SrvRecord&gt; records = ar.result());
            for (SrvRecord record: records) {
                System.out.println(record);
            }
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<p>Be aware that the List will contain the SrvRecords sorted by the priority of them, which means SrvRecords with smaller priority coming first in the List.</p>
<p>The SrvRecord allows you to access all informations contained in the SRV record itself:</p>
<pre class="prettyprint">SrvRecord record = ...
record.priority();
record.name();
record.priority();
record.weight();
record.port();
record.protocol();
record.service();
record.target();
</pre>
<p>Please refer to the API docs for the exact details.</p>
<h2 id="resolveptr">resolvePTR</h2><br/>
<p>Try to resolve the PTR record for a given name. The PTR record maps an ipaddress to a name.</p>
<p>To resolve the PTR record for the ipaddress 10.0.0.1 you would use the PTR notion of "1.0.0.10.in-addr.arpa"</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.resolveTXT("1.0.0.10.in-addr.arpa", new AsyncResultHandler&lt;String&gt;() {
    public void handle(AsyncResult&lt;String&gt; ar) {
        if (ar.succeeded()) {
            String record = ar.result());
            System.out.println(record);
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<h2 id="reverselookup">reverseLookup</h2><br/>
<p>Try to do a reverse lookup for an ipaddress. This is basically the same as resolve a PTR record, but allows you to just pass in the ipaddress and not a valid PTR query string.</p>
<p>To do a reverse lookup for the ipaddress 10.0.0.1 do something similar like this:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.reverseLookup("10.0.0.1", new AsyncResultHandler&lt;String&gt;() {
    public void handle(AsyncResult&lt;String&gt; ar) {
        if (ar.succeeded()) {
            String record = ar.result());
            System.out.println(record);
        } else {
            log.error("Failed to resolve entry", ar.cause());
        }
    }
});
</pre>
<h2 id="error-handling">Error handling</h2><br/>
<p>As you saw in previous sections the DnsClient allows you to pass in a Handler which will be notified with an AsyncResult once the query was complete. In case of an error it will be notified with a DnsException which will hole a DnsResponseCode that indicate why the resolution failed. This DnsResponseCode can be used to inspect the cause in more detail.</p>
<p>Possible DnsResponseCodes are:</p>
<h3 id="noerror">NOERROR</h3><br/>
<p>No record was found for a given query</p>
<h3 id="formerror">FORMERROR</h3><br/>
<p>Format error</p>
<h3 id="servfail">SERVFAIL</h3><br/>
<p>Server failure</p>
<h3 id="nxdomain">NXDOMAIN</h3><br/>
<p>Name error</p>
<h3 id="notimpl">NOTIMPL</h3><br/>
<p>Not implemented by DNS Server</p>
<h3 id="refused">REFUSED</h3><br/>
<p>DNS Server refused the query</p>
<h3 id="yxdomain">YXDOMAIN</h3><br/>
<p>Domain name should not exist</p>
<h3 id="yxrrset">YXRRSET</h3><br/>
<p>Resource record should not exist</p>
<h3 id="nxrrset">NXRRSET</h3><br/>
<p>RRSET does not exist</p>
<h3 id="notzone">NOTZONE</h3><br/>
<p>Name not in zone</p>
<h3 id="badver">BADVER</h3><br/>
<p>Bad extension mechanism for version</p>
<h3 id="badsig">BADSIG</h3><br/>
<p>Bad signature</p>
<h3 id="badkey">BADKEY</h3><br/>
<p>Bad key</p>
<h3 id="badtime">BADTIME</h3><br/>
<p>Bad timestamp</p>
<p>All of those errors are "generated" by the DNS Server itself.</p>
<p>You can obtain the DnsResponseCode from the DnsException like:</p>
<pre class="prettyprint">DnsClient client = vertx.createDnsClient(new InetSocketAddress("10.0.0.1", 53));
client.lookup("nonexisting.vert.xio", new AsyncResultHandler&lt;InetAddress&gt;() {
    public void handle(AsyncResult&lt;InetAddress&gt; ar) {
        if (ar.succeeded()) {
            InetAddress record = ar.result());
            System.out.println(record);
        } else {
            Throwable cause = ar.cause();
            if (cause instanceof DnsException) {
                DnsException exception = (DnsException) cause;
                DnsResponseCode code = exception.code();
                ...
            } else {
                log.error("Failed to resolve entry", ar.cause());
            }
        }
    }
});
</pre></div>
      </div>
    </div>
  </div>

</div>

</body>
</html>